I'm using the below method to check if a file is already in use... seems to work just fine but my problem is that if I have excel open, sometimes the filestream actually opens and leaves open the excel file that its currently checking.
Anyone know why the file is actually opening and not closing when it leaves the using statement?
EDIT: More to the above, it opens the excel file and then it display a message box telling me that the file is available to Read/Write
I put the below in the comments but I think it pertains to my usage of the IsFileLocked code and may actually be the real cause??
I'm using the IsFileLocked code along with a filewatcher. When the filewatcher goes off I check if the excel file is still in use and if its not in use then I query data back from that excel file.
Process.. 1.) Excel file has changed or is being changed by another user 2.) make sure its still not in use with the IsFileLocked method 3.) if file is no longer in use then query data back from the excel file but sometimes the excel file actually opens on the user's computer who is watching excel files for changes.. if this makes sense
protected virtual bool IsFileLocked(string path)
{
try
{
using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
{
}
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
}
//file is not locked
return false;
}