I have a problem that is driving me mad. Maybe you could help ;)
I'm tracking file changes on the folder with FileSystemWatcher and copy changed files to another folder. I don’t want to copy the file until it is done being saved. I cannot find a solution that works at the same time for all 3 scenarios below:
1) New file being copied into the folder 2) Existing file being overwritten by copying new one 3) File is opened by another process (i.e. Word) I have tried IsFileLocked method from the thread below. c# check if file is open
It will work for copying but the problem is that function will always return TRUE for opened OFFICE files (maybe for some others as well).
I also tried to check in the loop if the file size changes but it’s seems to be impossible as FileInfo.Length always return the target size (even though file is still being copied).
I'm using that function to check if file is in use
public static bool IsFileLocked(string path)
{
FileInfo fileInfo = new FileInfo(path);
FileStream stream = null;
try
{
stream = fileInfo.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (UnauthorizedAccessException)
{
// file created with readonly flag
return false;
}
catch (FileNotFoundException)
{
return false;
}
catch (IOException ex)
{
int errorCode = Marshal.GetHRForException(ex) & ((1 << 16) - 1);
bool islocked = errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
return islocked;
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
//file is not locked
return false;
}
Do you know how to distinguish if it's opened by some application or being copied?