tags:

views:

1181

answers:

5

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?

+2  A: 

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

Noldorin
+3  A: 

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 I use it in my nightly batches and it works, not elegant, but works.
systempuntoout
A: 

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

Rekreativc
+1  A: 

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.

Brian R. Bondy
A: 

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.