首页 > 解决方案 > C# Winform:对 FileSystemWatcher 路径使用全局变量

问题描述

我有一个带有两个 FileSystemWatcher 控件的表单。路径是通用的,我们需要在路径不同的多个环境中进行部署。我用我的全局变量在 Program.cs 中创建了一个类。

程序.cs

public static class Global {
    public const string connString = "<connection info>";
    public const string txtWatchPath = @"c:\test";
    public const string sumWatchPath = @"C:\Import";
}

我的观察者最初是这样设置的:

Form_Status.Designer.cs

// 
// txtWatcher
// 
this.txtWatcher.EnableRaisingEvents = true;
this.txtWatcher.Filter = "*_hdr.txt";
this.txtWatcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
this.txtWatcher.Path = Global.txtWatchPath;
this.txtWatcher.SynchronizingObject = this;
this.txtWatcher.Changed += new System.IO.FileSystemEventHandler(this.txtWatcher_Changed);
// 
// sumWatcher
// 
this.sumWatcher.EnableRaisingEvents = true;
this.sumWatcher.Filter = "*_hdr.sum";
this.sumWatcher.Path = Global.sumWatchPath;
this.sumWatcher.SynchronizingObject = this;
this.sumWatcher.Changed += new System.IO.FileSystemEventHandler(this.sumWatcher_Changed);

它最初可以工作,但是当我重新加载项目时,它们会解析为路径而不是全局变量。

Form_Status.Designer.cs

// 
// txtWatcher
// 
this.txtWatcher.EnableRaisingEvents = true;
this.txtWatcher.Filter = "*_hdr.txt";
this.txtWatcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
this.txtWatcher.Path = "c:\\test";
this.txtWatcher.SynchronizingObject = this;
this.txtWatcher.Changed += new System.IO.FileSystemEventHandler(this.txtWatcher_Changed);
// 
// sumWatcher
// 
this.sumWatcher.EnableRaisingEvents = true;
this.sumWatcher.Filter = "*_hdr.sum";
this.sumWatcher.Path = "C:\\Import";
this.sumWatcher.SynchronizingObject = this;
this.sumWatcher.Changed += new System.IO.FileSystemEventHandler(this.sumWatcher_Changed);

当我在设计器中创建控件时,我只是将路径设置为“C:\”,然后创建全局变量,并设置 .Path = 全局变量。
但是,当我保存项目时,全局变量被解析为实际路径。这意味着当我更改全局类上的路径变量时,它不会更改观察者的路径。

标签: c#winformsfilesystemwatcher

解决方案


推荐阅读