我已经看到关于这个问题的几个帖子。我已经实现了所有建议,例如在流编写器和连接对象上使用 flush() 、 close() 方法,使用 GC.Collect() 强制清理,使用 using{} 自动处理
我正在从数据库中执行简单的获取操作并写入文本文件..这是我的代码
public void WriteToFile(string ProductName)
{
//Already Got Data from DB and stored in "ProductName"
//saving in File
if (!File.Exists(path11))
{
File.Create(path11);
StreamWriter tw = new StreamWriter(path11);
tw.WriteLine(ProductName+"@"+DateTime.Now.ToString());
tw.Flush();
tw.Close();
}
else if (File.Exists(path11))
{
StreamWriter tw = new StreamWriter(path11, true);
tw.WriteLine(ProductName + "@" + DateTime.Now.ToString());
tw.Flush();
tw.Close();
}
GC.Collect();
}
我得到的另一个建议是锁定对象..但我无法实现它.. 任何建议都会有帮助
最佳答案
File.Create
创建文件并返回一个打开的流。你真的不需要所有的逻辑。只需使用 new StreamWriter(path11, true)
即可创建文件(如果不存在),如果存在则附加到文件。 使用
也很有帮助:
public void WriteToFile(string ProductName)
{
//Get Data from DB and stored in "ProductName"
using (var tw = new StreamWriter(path11, true))
{
tw.WriteLine(ProductName+"@"+DateTime.Now.ToString());
}
}
关于c# - 系统 IO 异常 : the process cannot access the file because it is being used by another process c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24226421/