filewatcher用于新创建或更改的文件

时间:2012-10-12 16:08:40

标签: c# winforms

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

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

4 个答案:

答案 0 :(得分:1)

您也可以将NotifyFilters.CreationTime用于新创建的文件。

NotifyFilters Enumeration

答案 1 :(得分:1)

MSDN page在此

上非常明确
// 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。ChangeType枚举包含一个Created值

答案 2 :(得分:1)

按照本文C#: Application to Watch a File or Directory using FileSystem Watcher

中列出的示例进行操作

您需要描述当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)

OnChanged

的示例处理程序
public static void OnChanged(object source, FileSystemEventArgs e)
{
   Console.WriteLine("{0} : {1} {2}", s, e.FullPath, e.ChangeType);
}

然后启用观察者发起事件:

fileSystemWatcher1EnableRaisingEvents = true;

答案 3 :(得分:0)

如果您为fileSystemWatcher1.Created

添加了事件处理程序,则上述操作应该有效