简体   繁体   English

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

[英]filewatcher for newly created or altered file

How do you check for a newly created file. 如何检查新创建的文件。 This only works for an edited file. 这仅适用于已编辑的文件。

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

You can use NotifyFilters.CreationTime for new created files as well. 您也可以将NotifyFilters.CreationTime用于新创建的文件。

NotifyFilters Enumeration NotifyFilters枚举

The MSDN page is really clear on this MSDN页面对此非常清楚

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

As you can see from this other page the e. 正如你从其他页面中看到的那样e。 ChangeType enum includes a Created value ChangeType枚举包含Created值

Following the example outlined in this article C#: Application to Watch a File or Directory using FileSystem Watcher 按照本文中概述的示例C#:使用FileSystem Watcher监视文件或目录的应用程序

You need to describe what has to be done when one of these attributes in fileSystemWatcher1.NotifyFilter gets altered by assigning different event handlers to different activities. 您需要描述当fileSystemWatcher1.NotifyFilter中的fileSystemWatcher1.NotifyFilter属性通过为不同的活动分配不同的事件处理程序而改变时必须完成的操作。 For example: 例如:

fileSystemWatcher1.Changed += new FileSystemEventHandler(OnChanged);
fileSystemWatcher1.Created += new FileSystemEventHandler(OnChanged);
fileSystemWatcher1.Deleted += new FileSystemEventHandler(OnChanged);
fileSystemWatcher1.Renamed += new RenamedEventHandler(OnRenamed);

With the signatures of both the handlers as 使用两个处理程序的签名

void OnChanged(object sender, FileSystemEventArgs e)
void OnRenamed(object sender, RenamedEventArgs e)

Example handler for OnChanged OnChanged示例处理程序

public static void OnChanged(object source, FileSystemEventArgs e)
{
   Console.WriteLine("{0} : {1} {2}", s, e.FullPath, e.ChangeType);
}

And then enable the watcher to raise events: 然后启用观察者引发事件:

fileSystemWatcher1EnableRaisingEvents = true;

如果您为fileSystemWatcher1.Created添加了事件处理程序,则上述操作应该有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM