2012-10-12 47 views
1

如何檢查新創建的文件。這僅適用於編輯的文件。新創建或更改文件的filewatcher

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

回答

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; 
+0

附加註意:不要忘記使用'InternalBufferSize'屬性。如果短時間內有很多變化,FileSystemWatcher緩衝區可能會溢出。這導致'FileSystemWatcher'失去跟蹤'Directory'中的變化。請參閱MSDN:http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.internalbuffersize.aspx – varg

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

真的清楚你可以從這個其他網頁電子看到的。 ChangeType枚舉包括創建值

0

如果你爲fileSystemWatcher1.Created添加了一個事件處理程序,上面應該可以工作。