如何检测新文件或修改过的文件

时间:2009-01-06 08:54:15

标签: winapi file

我发现有两种方法可以实现,ReadDirectoryChangesWFindFirstChangeNotification

我想知道它们,性能或其他方面有什么区别?

1 个答案:

答案 0 :(得分:5)

这是为Winapi标记的,但无论如何我用.net给它一个镜头。

您可以使用System.IO中的FileSystemWatcher类来实现此目的。

static void Main(string[] args)
{
    FileSystemWatcher fsw = new FileSystemWatcher("C:\\");
    fsw.Changed += new FileSystemEventHandler(fsw_Changed);
    fsw.Created += new FileSystemEventHandler(fsw_Created);
    fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);
    fsw.EnableRaisingEvents = true;
    fsw.IncludeSubdirectories = true;
    fsw.Renamed += new RenamedEventHandler(fsw_Renamed);

    Console.Read();
}

static void fsw_Renamed(object sender, RenamedEventArgs e)
{
    Console.WriteLine("{0} was changed to {1}", e.OldName, e.Name);
}

static void fsw_Deleted(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("{0} was deleted", e.Name);
}

static void fsw_Created(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("{0} was created", e.Name);
}

static void fsw_Changed(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("{0} was changed", e.Name);
}