问题
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?
回答1:
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...
回答2:
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)
回答3:
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
回答4:
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.
回答5:
Try putting the open command in a try-catch statement. If the file is being used IOException will be thrown.
回答6:
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.
来源:https://stackoverflow.com/questions/626058/file-used-by-another-process