C#文件读写操作的问题
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
for(;;)
{
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.Write(strLog);
//清空缓冲区
sw.Flush();
关闭流
sw.Close();
}
调用sw.Close()后,fs的写权限就变成false了,再次new StreamWriter sw 会出错,怎么解决?
------解决方案--------------------lz可以试一下
把 fs = new FileStream(path, FileMode.Append, FileAccess.Write);
放到 for内~
------解决方案--------------------或者把 Close放到for外
------解决方案--------------------
看楼主代码,感觉sw创建和关闭都应该放在for外,for内只写
------解决方案--------------------把sw.close()放在for循环的外面
------解决方案--------------------你也可以用Using 试一下,不用sw.Close();
------解决方案-------------------- #region 日志相关
/// <summary>
/// 写日志文件
/// </summary>
/// <param name="log"></param>
public static void WriteLog(string log)
{
string filename = GetAppPath() + "Log" + DateTime.Today.ToString("yyyyMMdd") + ".log";
WriteLog(log, filename);
}
/// <summary>
/// 写日志文件
/// </summary>
/// <param name="log">日志字符串</param>
/// <param name="filename">日志文件名(包含完整路径)</param>
public static void WriteLog(string log, string filename)
{
try
{
StreamWriter sw = File.AppendText(filename);
sw.WriteLine(log);
sw.Flush();
sw.Close();
}
catch
{}
}
#endregion