I am using fileSystemWatcher in C# winforms to monitor new files and folders created in the c:\Backup
Folder, my clients transfer files to this folder and my application is supposed to zip newly created files and folders and sends them with email.
I have no problem with Watcher and its events and it's working fine.
my question is how can I know if copying large files to c:\Backup
is finished so my app can start zipping them and send them?
Update : i just found out that every file copied raises the
Created
event first and then at the start of copying raisesChanged
event and after copy is finished it raisesChanged
event again.
so after reading Useful comments and some workaround, I found a solution that may not be the best way but I think it's doing the job.
async private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{
listBox6.Items.Add(e.FullPath + " " + e.ChangeType);
FileInfo file = new FileInfo(e.FullPath);
if (file.Attributes != FileAttributes.Directory)
{
Action lbl = () => { listBox7.Items.Add(e.Name + " copy in progress"); };
await Task.Run(() =>
{
while (IsFileLocked(file))
{
//some code like progressbar can be here
//this.Invoke(lbl);
}
}).ConfigureAwait(true);
}
listBox7.Items.Add(e.Name + " copied!");
}
and the method to check for file Lock (I just got it from mong zhu's comment):
bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, 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
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}