File used by another process<>
This question already has an answer here:
- Is there a way to check if a file is in use? 17 answers
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...
The only option here is to catch the generated exception and handle it appropriately. See these other two SO threads for full discussions:
- How to check for file lock?
- Detecting whether a file is locked by another process (or indeed the same process)
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
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.
Try putting the open command in a try-catch statement. If the file is being used IOException will be thrown.
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.