888*_*888 5 c# filesystemwatcher visual-studio-2010 visual-studio-2012
我在Visual Studio 2010中使用C#和框架4.0.
在我的项目中,有两种不同的形式,有两个FileSystemWatchers属性EnableRaisingEvent设置为false.如果我关闭Visual Studio,当我重新打开它时,我会将FileSystemWatcher属性EnableRaisingEvent设置为true.
在设计器文件中的两个表单中都有以下代码:
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.fileSystemWatcher1 = new System.IO.FileSystemWatcher();
((System.ComponentModel.ISupportInitialize)(this.fileSystemWatcher1)).BeginInit();
this.SuspendLayout();
this.fileSystemWatcher1.Filter = "my_filter";
this.fileSystemWatcher1.NotifyFilter = System.IO.NotifyFilters.LastWrite;
this.fileSystemWatcher1.SynchronizingObject = this;
this.fileSystemWatcher1.Changed += new System.IO.FileSystemEventHandler(this.fileSystemWatcher1_Changed);
}
Run Code Online (Sandbox Code Playgroud)
该属性EnableRaisingEvent未设置,但默认值为false.
知道为什么我会得到这种奇怪的行为吗?
编辑
我按照Virtlink的建议,添加了以下代码:
this.fileSystemWatcher1.EnableRaisingEvents = false;
Run Code Online (Sandbox Code Playgroud)
它似乎解决了我的问题,但几天后(以及一些开放,关闭和重建项目,但没有修改fileSystemWatcher1)我发现:
在设计师,在属性fileSystemWatcher1,EnableRaisingEvents被设置回来true
在代码中,先前添加的行丢失了
我尝试转移到Visual Studio 2012(仍然是框架4.0),并且解决方法将问题解决了几天.然后我得到了与VS10相同的情况.
还有其他想法吗?
它也会发生在 Visual Studio 2012 中,并且您不必关闭 Visual Studio。重新打开表单设计器足以将属性设置为True,无论是在设计器中可视化还是在运行时。
这似乎是 中的一个错误FileSystemWatcher。
解决方法是将此行显式添加到您的InitializeComponent:
this.fileSystemWatcher1.EnableRaisingEvents = false;
Run Code Online (Sandbox Code Playgroud)
如果设计师不与你合作,你就必须与之对抗。您放入的任何内容都InitializeComponent可能被设计者覆盖或删除,这InitializeComponent也是设计者的领域。处理此问题的一种方法是在表单构造函数中的调用之后添加该行。InitializeComponent
InitializeComponent();
this.fileSystemWatcher1.EnableRaisingEvents = false;
Run Code Online (Sandbox Code Playgroud)
这意味着设计者不会向您显示 的正确值EnableRaisingEvents,但由于它无论如何都不能很好地工作,因此可能不是什么大问题。将这条线放入构造函数中可确保设计者在将来的任何时候都不会删除它。