如何用c#编写文件系统监视程序

本文关键字:文件 系统监视 程序 何用 | 更新日期: 2023-09-27 17:53:25

我用c#写了一个小应用程序,它涉及到filesystemweather来监视一个特定的文件夹。一旦文件更新,它就打开一个串行端口,并将文件内容写入串行端口。但有时文件在4-5小时内不会更新。文件系统监视程序似乎进入睡眠状态,并且在文件更新后不响应。

下面是我的代码:
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");
}

这里有任何指针

如何用c#编写文件系统监视程序

如果dotnet中存在导致FileSystemWatcher"超时"的问题,可以说:一个快速的解决方案是使用计时器控件并每隔一段时间重新初始化FileSystemWatcher,这样它就不会"超时"。您可以访问dotnet调试符号服务器,这样您就可以自己调试FileSystemWatcher,看看它是怎么做的。

可能FSW对象正在被垃圾收集,因为它超出了作用域。

在上面的代码中,你没有显示你在哪里定义了"观察者"对象。

如果它在您使用它的相同方法中定义,可能这就是问题所在。尝试在类的顶部(在任何方法之外)定义它。