C# Code To Overcome "The Process Cannot Access The File XYZ Because It Is Being Used By Another Process" Error

In this article, I going to give the shortest solution for the error “The Process Cannot Access the file XXX because it is being used by another Process”.

My Code

if (!File.Exists(FileName))
{
    File.Create(FileName);
}

File.AppendAllText(FileName, MyStringBuilder.ToString());

The above one is my code. I am trying to create a file using the specific path if the file does not exist. Then, I'm trying to append my StringBuilder text into that file.

When I ran the above code while appending - I got the error “The Process Cannot Access the file XXX(FilePath) because it is being used by another Process”. So, I searched on many sites to overcome this error but couldn't find the exact solution to solve this.

Here are some answers,

FilePath

Source: www.stackoverflow.com

Accepted Solution

Source: www.stackoverflow.com

Error

Source: www.stackoverflow.com

Same Error

Source: www.stackoverflow.com

Sign In

Source: www.stackoverflow.com

Finally, I got the reason why this error is rising at that particular point.

Because you’re not disposing of File Instance, a lock remains on that File with another process. To overcome this error, I changed the code to,

MyCode

if (!File.Exists(FileName))  
{
    File.Create(FileName).Dispose();  
}

File.AppendAllText(FileName, MyStringBuilder.ToString());

By adding Dispose in the File creation part, the lock is released after the file is created. That means we implemented a DISPOSE method to release unmanaged resources used by the application. In the above (top first) code, when we created the file using the Create method, the resources were allocated to that file, and the Lock was appended.

By calling the DISPOSE method, we are releasing the memory (Objects) that is allocated to that file. We should call this method after file processing is finished. Otherwise, it will throw an EXCEPTION "Access Denied" or the file is being used by another program.

Close() Method

Here, we may have the question, why can we not also use the Close() method to release the file resources? Yes, both methods are used for the same purpose. Even by calling the DISPOSE method it calls the Close() method inside.

void Dispose()  
{  
    this.Close();  
}

But there is some a slight difference in both behaviors. For example -- Connection Class. If the close method is called, then it will disconnect with the database and release all resources being used by the connection object, and the open method will reconnect it again with a database without reinitializing.

However, the Dispose method is used to completely release the connection object and cannot be reopened just by calling the open method.

I hope this article is useful. Thank You.


Recommended Free Ebook
Similar Articles