I have a C# utility that needs perform some actions as soon as a specific file is released by another process, i.e. that process stops writing into the file. I am using the code below but it's behaving inconsistently on a Windows 7 system.
private static bool FileWritten(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open,
FileAccess.Read,
FileShare.None))
{
return true;
}
}
catch (IOException e)
{
return false;
}
}
Sometimes it would return false even though it seems that the file has already been released. I am calling FileWritten() in a while(true) loop that keeps checking calling FileWritten() as long as it returns false, and then exits after some max time. Debugging this is difficult since it seems to work fine under debugger (i.e. it returns true as soon as the file is actually released) but then does not work when I launch my code directly. Also, even adding debug prints seems to affect its behavior.
Is there a more reliable way to check if a file has been written to and released, that would work Win 7 and, preferably, also on Win XP?