我已经用C#写了一个小的应用程序,它涉及到文件系统来监视特定的文件夹。一旦文件被更新,它就打开一个串口,并将文件内容写入串口。但有时文件在这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");
}关于这一点的任何建议。
发布于 2011-04-28 17:17:56
如果在dotnet中有一个问题导致FileSystemWatcher“超时”,per说:一个快速的解决办法是使用timer控件,并每隔一段时间重新初始化FileSystemWatcher,这样它就不会“超时”。您可以访问dotnet调试符号服务器,因此可以自己调试FileSystemWatcher以查看它的功能。
发布于 2014-06-28 00:05:42
也许FSW对象正在被垃圾收集,因为它超出了作用域。
在上面的代码中,您没有显示在何处定义"watcher“对象。
如果定义它的方法与您使用它的方法相同,那么这可能就是问题所在。尝试在类的顶部定义它(在任何方法之外)。
https://stackoverflow.com/questions/5800800
复制相似问题