Troubleshooting Error “The process cannot access the file because it is being used by another process”
You may come across the error “The process cannot access the file ‘abc.txt’ because it is being used by another process” while programming in DotNet environment. Usually this case occurs when you create a file and do some operation, before completion of the operation or if the file object is been available in memory and you try to either delete the file or rename or open using Read Write mode you will get this error.
Following are some of the problem case and solution to get through this error.
Problem Case – 1 : Created a file using file stream, and before closing the file stream object trying to delete the file or rename the file
Solution : Close the file stream, flush the file stream object before you do other processing
Best Practice: Open a file stream object in try block and close it in finally block
Problem Case – 2 : When you attach a file to System.Net.Mail.Attachment object and send an email, After the email is sent if you delete the file, You may get the same error
Solution : After the email has been sent, dispose the Attachment object manually, before deleting or renaming the file. You cannot open the file in Read Write Mode also if the file object is not disposed
Best Practice : In order to make sure the email has been sent properly before disposing the file object from memory, sleep for few second before disposing the file object
Problem Case – 3: When you open a file which has been already opened for Read Write Mode to write some content. This case may occur when you open a file in the parent method, and you need to write some content to file in child method also. so when you try to open the file again, You may get the same error.
Solution : Instead of reopening the file again, you can pass the file object as a reference argument to the child method
There are several other occasions where you may face the error “The process cannot access the file ‘abc.txt’ because it is being used by another process”, The main reason is that the object instance is still available in main memory.
Source: Tech notes

