很久没有用.net对文件进行操作了,很生疏。
错误为“正由另一进程使用,因此该进程无法访问该文件”。请教一下大家,文本流在哪里打开了没有关闭?using System;
using System.IO;public partial class test2 : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //获取所在目录路径
            string path = Server.MapPath("./");
            string fpath = path + "detial-" + 1 + ".html";
            if (File.Exists(fpath)) File.Delete(fpath);
            File.Create(fpath);
            //写入数据
            using (StreamWriter sw = new StreamWriter(fpath))
            {
                sw.Write("content");
                sw.Flush();
                sw.Close();
                sw.Dispose();
            }
        }
    }
}

解决方案 »

  1.   

    File.Create(fpath);返回一个FileStream,没有关闭。
    改成
    FileStream fs = File.Create(fpath);
    fs.Close();
      

  2.   

    愚蠢了一回,改成这样更简单:
                using (StreamWriter sw = new StreamWriter(File.Create(fpath));
                {
                    sw.Write("content");
                    sw.Flush();
                }//既然用了using会自动dispose
      

  3.   

    FileStream   fs = new FileStream("",FileMode.Open,FileAccess.Write);
    using (StreamWriter sw = new StreamWriter(fs,Encoding.Default))
                {
                    sw.Write("content");
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }
       fs.Close();   fs = new FileStream("",FileMode.Open,FileAccess.Read);
       StreamReader sr = new StreamReader(fs,Encoding.Default);
       StringBuilder output = new StringBuilder();
       string rl;
       while((rl=sr.ReadLine())!=null)
       {
        output.Append(rl+"");
       }
       lblFile.Text = output.ToString();
       sr.Close();
       fs.Close();
      

  4.   

    File.Create已经创建流,没有关闭
    不许使用File类操作,直接使用下面的就可以了
    using (StreamWriter sw = new StreamWrite(fpath,false,System.Text.Encoding.Default)))
    {
        //第二个参数false时当存在就覆盖,不存在就创建
    }