gpt4 book ai didi

c# - 在 C# 中检查文件系统监视器

转载 作者:太空宇宙 更新时间:2023-11-03 19:57:00 24 4
gpt4 key购买 nike

我已经编写了这段代码来监视我系统中的文件,但它不会提醒文件夹或文件中的任何修改。我怎样才能做到这一点?我不明白,因为它没有显示任何异常或错误。

static void Main(string[] args)
{
FileSystemWatcher();
}

public static void FileSystemWatcher()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"D:\watcher";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
Console.Read();
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + " has changed");
}

最佳答案

我更新了代码。如果要查看添加的新文件,则需要扩展 NotifyFilter

    static void Main(string[] args)
{
FileSystemWatcher();
}

public static void FileSystemWatcher()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"D:\temp";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += Watcher_Created;
watcher.Renamed += Watcher_Renamed;
watcher.EnableRaisingEvents = true;
Console.Read();
}

private static void Watcher_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine(e.Name + " has been renamed");
}

private static void Watcher_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + " has been added");
}

private static void OnChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + " has changed");
}

关于c# - 在 C# 中检查文件系统监视器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32482395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com