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

守給你的承諾、 提交于 2019-11-29 08:08:20

Dont call Dispose() and Close() on the FileStream and StreamWriter, this will be handled automatically by the using-clause.

use a utility like filemon to check which processes are using the file.

UPDATE: From what i read Process monitor is very much similar to filemon. from either of these tools you can find which process accessed your file at what point. you can add a filter for your file before you start monitoring.

the other thing you could try is to get a lock on the file if it exists.

Maybe the file is accessed by virus scanner or windows indexing service?

Try writing the file to another directory outside of the debug folder.

Just a "wild shot" - does it help if you place the file in a more predictable location like 'c:\all_results.txt'?

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.

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.

Pedro:

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.

Or, alternatively, collect your text in a StringBuilder or some other in-memory text storage and then dump the text to the file once the loop finishes.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!