如何在C#中编写文件系统观察器?

| 我已经使用C#编写了一个小型应用程序,其中涉及Filesystemwather来监视特定的文件夹。一旦文件被更新,它将打开一个串行端口并将文件内容写入该串行端口。但是有时文件不会在4-5个小时内更新。而且似乎filesystemwatcher进入睡眠状态,并且在文件更新后没有响应。 这是我的代码:
FileSystemWatcher watcher = new FileSystemWatcher();

watcher.Path = @\"Z:\\\";
watcher.EnableRaisingEvents = true;
watcher.NotifyFilter = NotifyFilters.LastAccess;

watcher.Filter = \"*.wsx\";
watcher.Changed += new FileSystemEventHandler(OnChanged);

Console.WriteLine(\"Press \\\'q\\\' to quit the sample.\");
while (Console.Read() != \'q\') ;

public static string CrL = \"\\r\\n\";

private static void OnChanged(object source, FileSystemEventArgs e)
{
    string FileName;
    FileName = e.FullPath;

    Console.WriteLine(\"File: \" + e.FullPath + \" \" + e.ChangeType);
    Console.WriteLine(\"FILE is changed 1\");
    SerialPort port = new SerialPort(\"COM1\");

    port.Encoding = Encoding.ASCII;
    port.Open();

    using (System.IO.TextReader reader = System.IO.File.OpenText(e.FullPath))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            port.Write(line);
            port.Write(CrL);
        }
    }

    port.Close();

    Console.WriteLine(\"FILE is sent to com port\");
}
关于这一点的任何指针。     
已邀请:
如果说dotnet中有一个问题导致FileSystemWatcher超时,则可以这样说:一种快速的解决方法是使用计时器控件并经常重新初始化FileSystemWatcher,这样就不会超时\”。您可以访问dotnet调试符号服务器,因此可以自己调试FileSystemWatcher来查看其功能。     
也许FSW对象正在被垃圾回收,因为它超出了范围。 在上面的代码中,您没有显示定义“ watcher”对象的位置。 如果在使用它的相同方法中定义了它,则可能是问题所在。尝试在类的顶部(在任何方法之外)定义它。     

要回复问题请先登录注册