tags:

views:

270

answers:

1

Hi,

I'm downloading a file from a server and opening it using Process.Start() and attaching a file watcher to the file to catch any changes and re-upload them to the server.

Is there anyway to determine when the file has closed using the FileWatcher or any other method? The problem being I can't decide how to stop watching the file and I don't want it watched indefinitely?

Any ideas?

Thanks in advance

Jon

+1  A: 

What I did was put a 5 minute loop and just watch for the file to be available. That way I could give it time to free up, but yet still had a definitive time. If it hasn't cleared by 5 minutes in my system something is definetely wrong. You should set your time limit to your circumstances. I got this idea from somewhere, no idea where anymore.

        DateTime EndTime = System.DateTime.Now.AddMinutes((double)timeOut);

        while (System.DateTime.Now <= EndTime)
        {
            try
            {
                using (Stream stream = System.IO.File.Open(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    if (stream != null)
                    {
                        break;
                    }
                }
            }
            catch (FileNotFoundException)
            {
                //
            }
            catch (IOException)
            {
                //
            }
            catch (UnauthorizedAccessException)
            {
                //
            }


            System.Threading.Thread.Sleep(sleepTime);
        }
Alex