【发布时间】:2014-05-08 02:27:16
【问题描述】:
编辑:问题已解决,请参阅下面的答案。
我无法通过其他方法访问 FileSystemWatcher。
编辑:根据要求提供更多代码。
public static void watch(string path)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.DirectoryName |
NotifyFilters.FileName |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Security |
NotifyFilters.Size;
watcher.Filter = "*.*";
watcher.IncludeSubdirectories = true;
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
// The reason for having this try block (and EnableRaisingEvents toggling) is to solve a known problem with FileSystemWatcher, in which the event is fired twice.
try
{
MessageBox.Show("File changed.");
watcher.EnableRaisingEvents = false; // Error: The name 'watcher' does not exist in the current context
}
finally
{
watcher.EnableRaisingEvents = true; //Error: The name 'watcher' does not exist in the current context
}
}
我想更改EnableRaisingEvents 属性。
由于范围问题,我不能这样做。通常我会做的是在更大范围的某个地方声明FileSystemWatcher,但我不能在这里这样做,因为每次运行该方法时都必须创建一个新的。
那么,如何通过不同的方法更改对象的属性?
PS:我已经四处搜索,尝试了不同的方法,但最终没有任何效果。
编辑:澄清一下,我必须将 FileSystemWatcher 声明保留在方法内部(而不是给它更大的范围,从而允许它被另一种方法修改)。这样做的原因是我每次运行该方法时都需要创建一个新的。
【问题讨论】:
-
如果应该从多个
watch调用创建多个观察者,那么someOtherMethod应该如何决定使用哪一个? -
有什么原因不能只作为方法参数传递吗?
-
@Servy 抱歉,我忘了说“someOtherMethod”实际上是一个事件处理程序,所以谁调用它并不重要。
-
您是否意识到您的问题与 FileSystemWatcher 无关?这是一个普遍的“我如何以两种不同的方法访问变量”的问题。
-
FileSystemWatcher watcher = new FileSystemWatcher(); watcher.WhateverEvent += eventHandler;。访问sender参数以返回您的观察者。千万不要Dispose观察者。
标签: c# .net filesystemwatcher