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

前端 未结 10 1425
执念已碎
执念已碎 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: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

提交回复
热议问题