Is it possible to implement Delegate methods for FileSystemWatcher?
I have a delegate method named myDelegate which I want to call inside the timer function OnElapsedTimer, I tried calling myDelegate to invoke, OnDeleted, but the second argument is giving an compilation error. How can I pass FileSystemEventArgs in the delegate method?
using System;
using System.IO;
using System.Security.Permissions;
using System.Timers;
public class Watcher
{
public delegate void myDelegae(object source, FileSystemEventArgs e);
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnElapsedTimer);
aTimer.Interval = 5000;
aTimer.Enabled = true;
Run();
while (Console.Read() != 'q') ;
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
string path = @"C:\\File";
FileSystemWatcher watcher = new FileSystemWatcher(path);
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Attributes;
watcher.NotifyFilter = NotifyFilters.DirectoryName;
// Add event handlers.
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
private static void OnDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: {0}", e.FullPath);
}
private static void OnElapsedTimer(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
if (!Directory.Exists("C:\\File"))
{
//Invoke OnDeleted here
var fseArgs = new FileSystemEventArgs(WatcherChangeTypes.Deleted, @"C:\", @"File");
OnDeleted("C:\\File",fseArgs);
}
}
}
I’m assuming that you’re trying to call
OnDelete(e)insideOnElapsedTimer(), which of course fails because thateis of typeElapsedEventArgs, and notFileSystemEventArgs.The way to make this work is to create your own
FileSystemEventArgsobject, and pass that toOnDelete(). There’s nothing special about the class, it simply stores information relevant to the operation that was performed. In this case, you know what that operation is: The directory called “C:\File” has been deleted:Note that you’re almost certainly better off just listening in the
OnDelete()handler itself; why reproduce functionality that already works?