Chris Rutherford
Chris Rutherford

Reputation: 1672

File Watching in C# (.Net Core)

I have a project that requires file watching, and I thought I had the file watching covered, but the events for file system events are not firing.

Here is the code:

    static void Main(string[] args)
    {
        FileSystemWatcher fsw = new FileSystemWatcher();
        fsw.Path = args[0] != null ? args[0] : @"/files/";
        fsw.Created += Fs_Created;
        fsw.Changed += Fs_Changed;
        fsw.Deleted += Fs_Deleted;
        fsw.Renamed += Fs_Renamed;

        Console.WriteLine("Waiting for Files....");
        Console.WriteLine("(Press Any Key To Exit)");
        Console.ReadLine();
    }

    private static void Fs_Renamed(object sender, RenamedEventArgs e)
    {
        Console.WriteLine($"File {e.OldName} has been renamed to {e.Name}");
    }

    private static void Fs_Deleted(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine($"File {e.Name} has been deleted.");
    }

    private static void Fs_Changed(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine($"File {e.Name} Has Been Changed");
    }

    private static void Fs_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine($"File {e.Name} is new to the Directory");
    }
}

This is just to get the example across, but the issue is that there is no output in the console when fs events occur. Change, Delete, Rename, Create, nothing.

Is there something different in .net core for this? I've looked at three different examples, and all are similar. I have seen the event handler called instantiated like this: fsw.Created += new FileSystemEventHandler(Fs_Created);

Upvotes: 0

Views: 158

Answers (1)

Neil
Neil

Reputation: 11909

You seem to be missing fsw.EnableRaisingEvents = true;

Upvotes: 1

Related Questions