FileSystemWatcher stops catching events

后端 未结 3 859
北荒
北荒 2020-12-09 17:42

I am writing a c# program to let me know when a file has been added or deleted. I run it on my Windows 7 machine and watch an FTP server on our network.

It works

3条回答
  •  半阙折子戏
    2020-12-09 18:17

    I needed to add an error handler for the FileSystemWatcher

    fileSystemWatcher.Error += new ErrorEventHandler(OnError);
    

    And then add this code:

    private void OnError(object source, ErrorEventArgs e)
    {
        if (e.GetException().GetType() == typeof(InternalBufferOverflowException))
        {
            txtResults.Text += "Error: File System Watcher internal buffer overflow at " + DateTime.Now + "\r\n";
        }
        else
        {
            txtResults.Text += "Error: Watched directory not accessible at " + DateTime.Now + "\r\n";
        }
        NotAccessibleError(fileSystemWatcher ,e);
    }
    

    Here is how I reset the SystemFileWatcher object:

       static void NotAccessibleError(FileSystemWatcher source, ErrorEventArgs e)
        {
            source.EnableRaisingEvents = false;
            int iMaxAttempts = 120;
            int iTimeOut = 30000;
            int i = 0;
            while (source.EnableRaisingEvents == false && i < iMaxAttempts)
            {
                i += 1;
                try
                {
                    source.EnableRaisingEvents = true;
                }
                catch
                {
                    source.EnableRaisingEvents = false;
                    System.Threading.Thread.Sleep(iTimeOut);
                }
            }
    
        }
    

    I think this code should do what I want it to do.

提交回复
热议问题