To avoid exceptions like
(1) Process cannot access the file because it was used by another process
I used the following method to test the accessibility of the file before any further processing.
private bool CheckIfFileBeingUsed(string FilePath)
{
FileStream Fs = null;
try
{
Fs = File.Open(FilePath, FileMode.Open, FileAccess.Read, FileShare.None);
Fs.Close();
}
catch (Exception)
{
return true; //Error File is being used
}
return false; //File is not being used.
}
Could anyone advise me there’s any Windows API or other solutions for such testing of file accessibility instead of the above File.Open Method ?
It seems like you’re duplicating effort here. Since trying to open the file for processing will throw the same exception you’re catching here, why not just proceed with an attempt at processing the file, and handle the exception if it comes up?
Assuming that’s not possible for some reason, testing like this still isn’t totally reliable, since you now have a race condition. Even if this test passes, there’s no guarantee that the file will be in the same state when you go to run your other code on the file. That’s why it’s easier to just attempt to do what you want, and handle any exceptions at that point.