C# 添加带有子目录的文件夹时的FileSystemWatcher事件
我正在使用FileSystemWatcher监视目录中创建的新文件夹。这将很好地工作,除了这些文件夹中的每个都可以有一个或多个子目录 问题是,当我复制顶层文件夹(其中包含一个或多个子目录)时,FileSystemWatcher只捕获顶层文件夹的添加,而不捕获子目录 Ex:将带有子目录“bar”的文件夹“foo”拖动到正在监视的目录中 FileSystemWatcher通知新目录“foo”已创建,但未说明“bar”C# 添加带有子目录的文件夹时的FileSystemWatcher事件,c#,filesystemwatcher,C#,Filesystemwatcher,我正在使用FileSystemWatcher监视目录中创建的新文件夹。这将很好地工作,除了这些文件夹中的每个都可以有一个或多个子目录 问题是,当我复制顶层文件夹(其中包含一个或多个子目录)时,FileSystemWatcher只捕获顶层文件夹的添加,而不捕获子目录 Ex:将带有子目录“bar”的文件夹“foo”拖动到正在监视的目录中 FileSystemWatcher通知新目录“foo”已创建,但未说明“bar” 我是否缺少FileSystemWatcher的功能,或者是否有其他解决方法?您需要
我是否缺少FileSystemWatcher的功能,或者是否有其他解决方法?您需要设置哪个将获取或设置是否监视子目录的值。您需要设置
IncludeSubdirectories
属性
看看这个
“如果要监视指定目录中包含的文件和目录的更改通知,请将IncludeSubDirectory设置为true”
你还需要处理,以及
发件人:
复制和移动文件夹
操作系统和FileSystemWatcher对象解释
剪切粘贴操作或移动操作作为文件夹的重命名操作
以及它的内容。如果将包含文件的文件夹剪切并粘贴到
正在监视的文件夹中,FileSystemWatcher对象仅报告
文件夹是新的,但不是它的内容,因为它们本质上只是
重新命名
被通知文件夹的内容已被移动或复制
在监视的文件夹中,提供OnChanged和OnRename事件处理程序
方法
在此特定情况下,设置IncludeSubDirectory不起作用 下面是我设置的一个示例:
static void Main(string[] args)
{
FileSystemWatcher fsw = new FileSystemWatcher(@"C:\Temp", "*.*");
fsw.EnableRaisingEvents = true;
fsw.Created += new FileSystemEventHandler(fsw_Created);
fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
fsw.Changed += new FileSystemEventHandler(fsw_Changed);
fsw.IncludeSubdirectories = true;
Console.ReadLine();
}
static void fsw_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was changed.", e.FullPath);
}
static void fsw_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine("{0} was renamed.", e.FullPath);
}
static void fsw_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was created", e.FullPath);
}
在这种情况下,如果我将其中包含bar文件夹的foo移动到C:\Temp中,我将只收到创建了C:\Temp\foo的通知
FileSystemWatcher不是密封的,如果这个功能很重要,我会对它进行子类化,并扩展它以在创建的文件夹下进行检查,并为它们引发事件(或类似于此实现的事件).据我所知,没有办法让
文件系统监视程序
通知您目录中已更改的每个元素。
如果修改的元素是一个目录,您必须自己进行浏览(这并不难)
IncludeSubdirectories
只告诉您所监视元素中的文件和文件夹的修改情况,但如果在一次移动中复制了,则不会告诉您。在您的示例中,当您观看foo时,有人(稍后)向bar添加了一个文件,并且您已经设置了IncludeSubdirectories
,您将收到该更改的通知
嗯
马里奥
static void Main(string[] args)
{
FileSystemWatcher fsw = new FileSystemWatcher(@"C:\Temp", "*.*");
fsw.EnableRaisingEvents = true;
fsw.Created += new FileSystemEventHandler(fsw_Created);
fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
fsw.Changed += new FileSystemEventHandler(fsw_Changed);
fsw.IncludeSubdirectories = true;
Console.ReadLine();
}
static void fsw_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was changed.", e.FullPath);
}
static void fsw_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine("{0} was renamed.", e.FullPath);
}
static void fsw_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was created", e.FullPath);
}