创建文本后,写入文本,报“正由另一进程使用,因此该进程无法访问该文件”

编辑器加载中...

//检查文件,如果文件不存在则创建
private void ExistsFile(string FilePath)
{
//if(!File.Exists(FilePath))
//File.Create(FilePath);
//以上写法会报错,详细解释请看下文.........
if (!File.Exists(FilePath))
{
FileStream fs = File.Create(FilePath);
fs.Close();
}
}
private void Button2_Click(object sender, System.EventArgs e)
{
ExistsFile(Server.MapPath("test/weather.txt"));//检查文件是否存在
//读取文件
StreamReader sr = new StreamReader(Server.MapPath("test/weather.txt"), System.Text.Encoding.Default);
try
{
string input = sr.ReadToEnd();
sr.Close(); <div class="msgfont">//有的平台只有\n表示换行 如 mac,linux之流,windows平台换行使用\r\n
//所以就连.net框架都有一个&nbsp; System.Environment.NewLine; 以实现不同平台的换行.</div>
input = input.Replace("\r\n", "").Replace("\n", ""); //注:\r\n在winform中是换行,在html的文档内换行,显示出来的页面是不会换行的.
this.TextBox1.Text = input;
}
catch
{
Response.Write("<script>alert('文件读取失败');</script>");
}
}

private void Button1_Click(object sender, System.EventArgs e)
{
ExistsFile(Server.MapPath("test/weather.txt"));//检查文件是否存在
//写入文本
StreamWriter sr = new StreamWriter(Server.MapPath("test/weather.txt"),false,System.Text.Encoding.Default);
try
{
sr.Write(this.TextBox1.Text);
sr.Close();
Response.Write("<script>alert('文件写入成功');</script>");
}
catch
{
Response.Write("<script>alert('文件写入失败');</script>");
}
}

错误解释:

//当在指定路径没有文件的时候

//最初的方法:最开始调用

           if (!File.Exists(filePath))
                {
                    File.Create(filePath);
                }

//在进行读写操作的时候:



     private void Button2_Click(object sender, System.EventArgs e)
   {
    ExistsFile(Server.MapPath("test/weather.txt"));//检查文件是否存在
    //读取文件
    StreamReader sr = new StreamReader(Server.MapPath("test/weather.txt"), System.Text.Encoding.Default);
    try
    {
     string input = sr.ReadToEnd();
     sr.Close();
     input = input.Replace("\r\n", "").Replace("\n", "");
     this.TextBox1.Text = input;
    }
    catch
    {
     Response.Write("<script>alert('文件读取失败');</script>");
    }
   }


//就会出现“文件写的时候,正由另一进程使用,因此该进程无法访问该文件”

//分析问题是原因是:File.Create(FilePath); 创建了文件,进程没有结束

//所以该用流创建文件

                if (!File.Exists(filePath))
                {
                    FileStream fs1 = File.Create(filePath);
                    fs1.Close();
                }



//当流创建文件后,关闭流,就不会出现类似的问题了.....

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值