Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force FileSystemWatcher to wait till the file downloaded?

I am downloading a file and want to execute the install only after the download is complete. How do I accomplish this? Seems like FileSystemWatcher onCreate event would do this but this happens in a different thread, is there a simple way to force the waiting part to happen in the same thread.

Code I have so far

 FileSystemWatcher w = new FileSystemWatcher(@"C:/downloads");
 w.EnableRaisingEvents = true;
 w.Created += new FileSystemEventHandler(FileDownloaded);

 static void FileDownloaded(object source, FileSystemEventArgs e)
 {
    InstallMSI(e.FullPath);
 }

I looked at SynchronizingObject and WaitForChangedResult but didn't get a solid working sample.

like image 949
satyajit Avatar asked Mar 08 '11 20:03

satyajit


1 Answers

Try:

FileInfo fInfo = new FileInfo(e.FullPath); 
while(IsFileLocked(fInfo)){
     Thread.Sleep(500);     
}
InstallMSI(e.FullPath);


static bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;
    try {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException) {
        return true;
    }
    finally {
        if (stream != null)
            stream.Close();
    }   
    return false;
}
like image 120
ukhardy Avatar answered Oct 14 '22 14:10

ukhardy