C# 写日志文件经常出现"正由另一进程使用,因此该进程无法访问该文件"

写日志文件经常出现"正由另一进程使用,因此该进程无法访问该文件",以下为解决方法:

public static void WriteLog(string _msg)
    {
        string folder = System.Web.HttpContext.Current.Server.MapPath("~/log");
        if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
 
        string filename = folder + "/" + DateTime.Now.ToShortDateString() + ".txt";
        if (File.Exists(filename))
        {
            FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter sr = new StreamWriter(fs);
            sr.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "\t" + _msg);
            sr.Close();
            fs.Close();
        }
        else
        {
            FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter sr = new StreamWriter(fs);
            sr.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "\t" + _msg);
            sr.Close();
            fs.Close();
        }       
    }

 

你可能感兴趣的:(C#,C#,因此该进程无法访)