C# The process cannot access the file ''' because it is being used by another process

前端 未结 10 1418
执念已碎
执念已碎 2020-12-18 08:34

The snippet of code was just supposed to write a string into a text file called \"all_results.txt\". I had errors implementing in File.WriteAllText. After searching the net

相关标签:
10条回答
  • 2020-12-18 09:08

    As others have stated, opening and closing the file repeatedly might be the issue. One solution not mentioned is to keep the file open for the duration of the processing. Once complete, the file can be closed.

    0 讨论(0)
  • 2020-12-18 09:10

    try putting Thread.Sleep(1000) in your loop. Like someone mentioned above, the file doesn't always get released in time for the next iteration of the loop.

    0 讨论(0)
  • 2020-12-18 09:11

    I found the post while I had similar problem. The given advises gave me an idea! So for this purpose I wrote the following method

    public static void ExecuteWithFailOver(Action toDo, string fileName)
    {
    
        for (var i = 1; i <= MaxAttempts; i++)
        {
            try
            {
                toDo();
    
                return;
            }
            catch (IOException ex)
            {
                Logger.Warn("File IO operation is failed. (File name: {0}, Reason: {1})", fileName, ex.Message);
                Logger.Warn("Repeat in {0} milliseconds.", i * 500);
    
                if (i < MaxAttempts)
                    Thread.Sleep(500 * i);
            }
        }
    
        throw new IOException(string.Format(CultureInfo.InvariantCulture,
                                            "Failed to process file. (File name: {0})",
                                            fileName));
    
    }
    

    then I used the method in the following way

        Action toDo = () =>
                       {
                           if (File.Exists(fileName))
                               File.SetAttributes(fileName, FileAttributes.Normal);
    
                           File.WriteAllText(
                               fileName,
                               content,
                               Encoding.UTF8
                               );
                       };
    
        ExecuteWithFailOver(toDo, fileName);
    

    Later analyzing the logs I have discovered that the reason of my troubles was an attempt to act against the same file from the parallel threads. But I still see some pro-s in using the suggested FailOver method

    0 讨论(0)
  • 2020-12-18 09:13

    Try using lock around your file operations. http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx

    0 讨论(0)
提交回复
热议问题