问题描述
我想,如果一个文件被创建,复制或移动到一个目录我看得到通知。
我只想得到,虽然有关文件通知,而不是目录
I'm trying to be notified if a file is created, copied, or moved into a directory i'm watching.I only want to be notified about the files though, not the directories.
下面是一些代码,我公司目前拥有的:
Here's some of the code I currently have:
_watcher.NotifyFilter = NotifyFilters.FileName;
_watcher.Created += new FileSystemEventHandler(file_created);
_watcher.Changed += new FileSystemEventHandler(file_created);
_watcher.Renamed += new RenamedEventHandler(file_created);
_watcher.IncludeSubdirectories = true;
_watcher.EnableRaisingEvents = true;
但问题是,如果我移动包含在其中的文件的目录,我得到了,没有事件文件。
Problem is, if I move a directory that contains a file in it, I get no event for that file.
我怎样才能得到它来通知我要添加的所有文件(不论如何)到监视目录或它的子目录?
How can I get it to notify me for all files added (regardless of how) to the watched directory or it's sub directories?
柜面我没有解释不够好......我的 WatchedDirectory 和 directory1目录的。的 directory1目录的包含的 hello.txt的的。如果我移动的 directory1目录的成的 WatchedDirectory 的,我想收到的的 hello.txt的的
Incase I didn't explain good enough... I have WatchedDirectory, and Directory1. Directory1 contains Hello.txt. If I move Directory1 into WatchedDirectory, I want to be notified for Hello.txt.
编辑:我要指出我的操作系统是Windows 8,而我做得到复制/粘贴事件的通知,但不动的事件(拖放到文件夹中)
I should note my OS is Windows 8. And I do get notification for copy/paste events, but not move events (drag and drop into the folder).
推荐答案
也许这种解决方法可以派上用场(但由于涉及递归我会小心的性能):
Maybe this workaround could come in handy (but I'd be careful about performance as it involves recursion):
private static void file_created(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Created)
{
if (Directory.Exists(e.FullPath))
{
foreach (string file in Directory.GetFiles(e.FullPath))
{
var eventArgs = new FileSystemEventArgs(
WatcherChangeTypes.Created,
Path.GetDirectoryName(file),
Path.GetFileName(file));
file_created(sender, eventArgs);
}
}
else
{
Console.WriteLine("{0} created.",e.FullPath);
}
}
}
这篇关于子目录中的文件FileSystemWatcher的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!