the title is pretty self explanatory.
the common used method:
protected virtual bool IsFileLocked(FileInfo file)
{
try
{
using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
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;
}
//file is not locked
return false;
}
does not work with ASCII-text file. I made a test with a python code that write to a text file continuously and in fact the method return FALSE (not locked) while in reality some other application was using the file to write on it.
i can check with a method if the file changes over a short period of time but this would be very inefficient if iterated over many files (i.e 500ms over 1000 files would be 8minutes wait).
one approach that actually works is to try to do File.Move()
and see if it returns an exception. if so the file is busy
. I dont like this approach because in case of problems it could damage the file since it
s actually doing an operation on the file itself.
this would be the implemented method
public bool IsFileLocked(string filePath)
{
try
{
string tempFilePath = filePath + ".tmp";
File.Move(filePath, tempFilePath);
File.Move(tempFilePath, filePath);
return false; // File is not locked
}
catch (IOException)
{
return true; // File is locked
}
catch (UnauthorizedAccessException)
{
return true; // File is locked or access is denied
}
}
any thought?