I have the following code that i use to monitor a directory for text files, the directory gets new files twice a day, the code works fine for sometime but after that it stops firing OnCreated event...
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public static void Run()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"c:\users\documents\";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Created += new FileSystemEventHandler(OnCreated);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
}
private static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
Cannot figure out the issue.
Also, I would like to know a foolproof alternative to this (if any), since I am not finding this reliable..
Because after the Run method has completed, watcher is eligible for garbage collection.
This means that after some time watcher will be collected and obviously will stop raising events.
To solve, keep a reference of the watcher in the outer scope:
private static FileSystemWatcher watcher;
public static void Run()
{
watcher = new FileSystemWatcher();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With