c# - 系统 IO 异常 : the process cannot access the file because it is being used by another process c#

标签 c# .net

我已经看到关于这个问题的几个帖子。我已经实现了所有建议,例如在流编写器和连接对象上使用 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/

相关文章:

c# - 定期从网络共享文件夹中读取文件的最有效方法是什么?

c# - 如何知道哪些过时的方法/API 被替换为

c# - 将日期添加到文件名时的 StreamWriter 问题

c# - 可变长度子串的最佳方法

.net - c#中Exception类的使用

.net - .Net TCP/IP 库有什么改进吗?

c# - HTML敏捷包: get all elements by class

c# - 使用 C# 在 Windows Server 2003 上查询 EventLog

c# - WCF4 (.NET Framework 4) 是否支持客户端连接池?

c# - 您如何自动调整 DataGridView 控件中的列大小并允许用户调整同一网格上的列大小?