【发布时间】:2012-03-29 01:30:32
【问题描述】:
感谢您对此的任何帮助..
我正在尝试编写一个小的 FileWatcher 应用程序来监视本地目录并将任何更改复制到另一个本地目录。我在 .Net 中使用了 FileSystemWatcher 类,并在我的 btnStart 单击上运行四个线程,每个线程都有自己的 FileSysWatcher 实例,监视不同的更改类型。所以我首先要查找的是 created 事件。
new Thread(Created).Start();
那么我有:
void Created()
{
FileSystemWatcher Watcher2 = new FileSystemWatcher();
Watcher2.Path = txtBxDirToWatch.Text;
Watcher2.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.DirectoryName;
//watch all files in the path
Watcher2.Filter = "*.*";
//dont watch sub dir as default
Watcher2.IncludeSubdirectories = false;
if (chkBxIncSub.Checked)
{
Watcher2.IncludeSubdirectories = true;
}
Watcher2.Created += new FileSystemEventHandler(OnCreated);
Watcher2.EnableRaisingEvents = true;
}
我想要做的只是将任何更改复制到硬编码的本地路径,但我无法得到任何结果。这是我处理事件的地方
public static void OnCreated(object source, FileSystemEventArgs e)
{
//combine new path into a string
string created = Path.Combine(@"C:\WatcherChanges", e.Name);
File.Create(created);
}
【问题讨论】:
-
你试过调试它吗?你的 OnCreated 是否被击中然后你创建文件?您确定 e.Name 是文件名,而不是完整的文件路径吗?
-
检查是否曾经创建过这个新线程,因为您正在从新线程访问 UI 控件。我相信它会引发异常,而您没有看到它。
标签: c# filesystemwatcher