文件系统监视文件夹并获取文件名

本文关键字:获取 文件名 文件夹 系统监视 文件 | 更新日期: 2023-09-27 18:11:45

我使用FileSystemWatcher来监视几个文件夹。当它触发更改事件时,我想获得已更改文件的文件名。因为当我尝试使用e.Name或e.FullPath时,监视程序正在监视文件夹,所以我得到了文件夹路径。

有办法得到文件名吗?

代码:它是一个观察者数组。

watchers[_Idx] = new FileSystemWatcher();
watchers[_Idx].Path = row.Cells[0].Value.ToString();
watchers[_Idx].IncludeSubdirectories = true;
watchers[_Idx].NotifyFilter = NotifyFilters.LastWrite | 
                          NotifyFilters.DirectoryName | NotifyFilters.FileName | 
                          NotifyFilters.Size;
watchers[_Idx].Changed += new FileSystemEventHandler(SyncThread);
watchers[_Idx].Created += new FileSystemEventHandler(SyncThread);
watchers[_Idx].Renamed +=new RenamedEventHandler(SyncThread);
watchers[_Idx].EnableRaisingEvents = true;

文件系统监视文件夹并获取文件名

您可以从事件中提取文件名:

// Define the event handlers.
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);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
    // Specify what is done when a file is renamed.
    Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}