C# 新创建或更改的文件的filewatcher

C# 新创建或更改的文件的filewatcher,c#,winforms,C#,Winforms,如何检查新创建的文件。这仅适用于已编辑的文件 DateTime time = DateTime.Now; // Use current time string format = "dMyyyy"; // Use this format string s = time.ToString(format); fileSystemWatcher1.Path = @"C:\Users\De

如何检查新创建的文件。这仅适用于已编辑的文件

        DateTime time = DateTime.Now;             // Use current time
        string format = "dMyyyy";            // Use this format
        string s = time.ToString(format); 



        fileSystemWatcher1.Path = @"C:\Users\Desktop\test\";
        fileSystemWatcher1.NotifyFilter =   NotifyFilters.LastAccess | 
                                            NotifyFilters.LastWrite | 
                                            NotifyFilters.FileName | 
                                            NotifyFilters.DirectoryName;

        fileSystemWatcher1.IncludeSubdirectories = false;
        fileSystemWatcher1.Filter = s + ".txt";

您也可以对新创建的文件使用
NotifyFilters.CreationTime

这一点上的问题非常清楚

// Add event handlers.
fileSystemWatcher1.Created += new FileSystemEventHandler(OnChanged);

// Enable the event to be raised
fileSystemWatcher1.EnableRaisingEvents = true;

// In the event handler check the change type
private static void OnChanged(object source, FileSystemEventArgs e)
{
    // Specify what is done when a file is changed, created, or deleted.
   Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
}

正如你从另一页看到的,e。enum包括一个创建的值

,遵循本文概述的示例

您需要描述当
fileSystemWatcher1.NotifyFilter
中的其中一个属性通过为不同的活动分配不同的事件处理程序而改变时必须执行的操作。例如:

fileSystemWatcher1.Changed += new FileSystemEventHandler(OnChanged);
fileSystemWatcher1.Created += new FileSystemEventHandler(OnChanged);
fileSystemWatcher1.Deleted += new FileSystemEventHandler(OnChanged);
fileSystemWatcher1.Renamed += new RenamedEventHandler(OnRenamed);
将两个处理程序的签名作为

void OnChanged(object sender, FileSystemEventArgs e)
void OnRenamed(object sender, RenamedEventArgs e)
更改后的
处理程序示例

public static void OnChanged(object source, FileSystemEventArgs e)
{
   Console.WriteLine("{0} : {1} {2}", s, e.FullPath, e.ChangeType);
}
然后使观察者能够引发事件:

fileSystemWatcher1EnableRaisingEvents = true;

如果您为fileSystemWatcher1添加了一个事件处理程序,上述操作应该可以正常工作。已创建

附加说明:不要忘记使用
InternalBufferSize
属性。如果在短时间内有许多更改,则
FileSystemWatcher
缓冲区可能溢出。这会导致
FileSystemWatcher
无法跟踪
目录中的更改。见MSDN: