22

Many a times we get an error, while trying to write file on Windows platform,

"The process cannot access the file 'XXX' because it is being used by another process."

How to check in C#, before writing to file that its not being used by another process?

NileshChauhan
  • 5,469
  • 2
  • 29
  • 43

6 Answers6

20

You can't, basically - you have to attempt to open the file for writing, and if you get an exception you can't write to it :(

Even if you could do a separate check first, the result would be out of date before you could start writing - you could still end up with the exception later.

It would be nice if the framework provided a TryOpen method, admittedly...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
9

The only option here is to catch the generated exception and handle it appropriately. See these other two SO threads for full discussions:

Community
  • 1
  • 1
Noldorin
  • 144,213
  • 56
  • 264
  • 302
8

You must to close your file after using it on your code:

FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read); //file is opened
//you use the file here 
file.Close(); //then you must to close the file
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
2

You simply have to try the open with the sharing access you would like, and handle the error that is thrown.

Note: Sometimes the file won't open simply because the file sharing rights you specified conflicts with the file sharing rights that someone already opened the file with.

Please see my answer here for more information.

Community
  • 1
  • 1
Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
1

Try putting the open command in a try-catch statement. If the file is being used IOException will be thrown.

David Božjak
  • 16,887
  • 18
  • 67
  • 98
0

Try to Rename the file if you are able to rename then it is confirm that no other process is accessing that file. Finally make sure that you have renamed the same file in the same folder.