How do I write a filesystem watcher in C#?
I have written a small application using C# which involves Filesystemwather to watch a particular folder. As soon as a file is updated it open up a serial port and writes the files contents to the serial port. But at times the file isn't upda开发者_运维问答ted for more this 4-5hours. And it seems like filesystemwatcher goes to sleep and doesn't respond after the file gets updated.
Here is my code:
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");
}
Any pointers on this one.
If there is an issue in dotnet that causes the FileSystemWatcher to "timeout", per say: a quick work-around would be to use a timer control and re-initialize the FileSystemWatcher every so often so it doesn't "timeout". You have access to the dotnet debug symbol servers so you could debug the FileSystemWatcher yourself to see what it does as well.
Maybe the FSW object is being garbage-collected because it's going out of scope.
In your code above you haven't shown where you're defining the "watcher" object.
If it's defined in the same method where you use it, maybe that's the problem. Try defining it at the top of your class (outside of any methods).
精彩评论