0

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

curtisk
  • 19,950
  • 4
  • 55
  • 71
Jon
  • 4,295
  • 6
  • 47
  • 56
  • 1
    You may find your answer in one of these: http://stackoverflow.com/questions/561467/filesystemwatcher-waitforchanged-returns-but-there-is-still-a-lock-on-the-file, http://stackoverflow.com/questions/699538/file-access-error-with-filesystemwatcher-when-multiple-files-are-added-to-a-direc – Fredrik Mörk Aug 21 '09 at 19:52

1 Answers1

1

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
  • 12,749
  • 3
  • 31
  • 45