windows - c# check if file is opened or being copied -


i have problem driving me mad. maybe ;)

i'm tracking file changes on folder filesystemwatcher , copy changed files folder. don’t want copy file until done being saved. cannot find solution works @ same time 3 scenarios below:

1) new file being copied folder 2) existing file being overwritten copying new 1 3) file opened process (i.e. word) have tried isfilelocked method thread below. c# check if file open

it work copying problem function return true opened office files (maybe others well).

i tried check in loop if file size changes it’s seems impossible fileinfo.length return target size (even though file still being copied).

i'm using function check if file 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 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;     }         {         if (stream != null)         {             stream.close();             stream.dispose();         }     }     //file not locked     return false; } 

do know how distinguish if it's opened application or being copied?


Comments