C#中的文件监视(.Net Core)

时间:2018-09-06 15:22:09

标签: c# asp.net-core

我有一个需要监视文件的项目,我以为可以监视文件,但是文件系统事件未触发。

这是代码:

    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");
    }
}

这只是为了使示例更容易理解,但问题是,发生fs事件时控制台中没有输出。更改,删除,重命名,创建,什么都没有。

.net核心中是否对此有所不同?我看了三个不同的例子,并且都是相似的。我已经看到称为这样的实例化事件处理程序:fsw.Created += new FileSystemEventHandler(Fs_Created);

1 个答案:

答案 0 :(得分:1)

您似乎丢失了fsw.EnableRaisingEvents = true;