This is how I do it at the moment. I try to open the file with the FileShare set to none. So I want exclusive accesss to the file. If I can't get that then its a good bet somebody else has the file locked.
There's got to be a better and faster way. Any ideas?
try
{
using (FileStream fs = File.Open(GetLockFilename(), FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
fs.Close();
}
// The file is not locked
}
catch (Exception)
{
// The file is locked
}
There is no need first to check if the file is locked and then access it, as between the check and the access some other process may still get a lock on the file. So, what you do is correct, if you succeed, do your work with the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With