系统IO异常:因为它正由另一个进程使用C#中的进程无法访问该文件进程、因为它、该文件、无法访问

2023-09-03 01:41:48 作者:||丶至尊↘少年﹌

我见过几个后这个问题。我已经实现了所有建议喜欢使用的flush(),close()方法上的StreamWriter和连接对象,请使用GC.Collect的()来强制清理,,使用使用{}来autodispose

I have seen several post for this problem .I have implemented all suggestion like using flush() , close() method on streamwriter and connection Object,use GC.Collect() to force cleanup,, use using{} to autodispose

我是做简单的从数据库获取操作和写入文本文件..here是我的code

I am Doing Simple Get Operation from DB and write to text file ..here is my Code

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();
}

另外一个建议,我得到的是锁定的对象..但我不能执行它.. 任何建议将是有益的。

Another suggestion I Got is to lock the object ..But I cannot implement it .. Any suggestion would be Helpful

推荐答案

File.Create 创建该文件,并返回一个打开的流。你并不真的需要所有的逻辑。只需使用新的StreamWriter(path11,真)这将创建文件,如果它不存在,并追加到它,如果它。此外使用是有帮助的:

File.Create creates the file and returns an open stream. You don't really need all that logic. Just use new StreamWriter(path11, true) which will create the file if it doesn't exist and append to it if it does. Also using is helpful:

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());
    }
}