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

  1. If(!File.Exists(FileName))  
  2. File.Create(FileName);  
  3. File.AppendAllText(FileName,MyStringBuilder.ToString());  

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

When I run 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 -
C#
Source:www.stackoverflow.com

C#
Source:www.stackoverflow.com
C#
Source:www.stackoverflow.com
C#
Source:www.stackoverflow.com

C#
Source:www.stackoverflow.com

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

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

MyCode

  1. If(!File.Exists(FileName))  
  2. File.Create(FileName).Dispose();  
  3. 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 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 file is being used by other program.

Close() Method

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

  1. Void Displose()  
  2. {  
  3.    this.Close();  
  4. }  

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

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

I hope this article is useful. Thank You.

Up Next
    Ebook Download
    View all
    Learn
    View all