使用FileSystemWatcher监控网络路径
2008-05-31 21:39:10 来源:WEB开发网本文示例源代码或素材下载
在VS2005中,.Net里面有个FileSystemWatcher控件,用来监控文件变化,它会通知文件创建,修改,删除的消息。网上这样的例子很多,但是在实际应用的时候,发现还有一些待处理的问题,我做了一个简单的demo,解决了如下的问题:
1. 多次连续触发 (通过一个定时器来解决)
2. 能监控网路路径 (serviceProcessInstaller的Account属性设置为NetworkService)
3. 通过windows service来实现, 做成安装文件方便注册服务
注意事项:
1. 切记网络路径要给guest的权限,否则监控不了。
2. 修改Service1代码中的watcher.Path。
3. 新建文件c: est.log,将此文件设置为可写的权限。
4. 安装完成后手动将服务启动。
关键代码:
public class AdvancedFileSystemWatcher : System.IO.FileSystemWatcher
{
public event NetworkPathUnavailableEventHandler NetworkPathUnavailable;
public delegate void NetworkPathUnavailableEventHandler(string Message);
public event NetworkPathAvailableEventHandler NetworkPathAvailable;
public delegate void NetworkPathAvailableEventHandler(string Message);
private System.Timers.Timer _myTimer = new System.Timers.Timer();
private bool _isNetworkUnavailable = false;
public AdvancedFileSystemWatcher()
{
_myTimer.Start();
}
public AdvancedFileSystemWatcher(int iNetworkWatchInterval)
{
if (iNetworkWatchInterval > 0)
{
_myTimer.Interval = iNetworkWatchInterval;
}
else
{
_myTimer.Interval = 2000;
}
_myTimer.Start();
}
public void close()
{
_myTimer.Stop();
_myTimer.Dispose();
}
private void _myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
DirectoryInfo myFolder;
try
{
myFolder = new DirectoryInfo(base.Path);
if (!_isNetworkUnavailable)
{
if (!myFolder.Exists)
{
_isNetworkUnavailable = true;
if (NetworkPathUnavailable != null)
{
NetworkPathUnavailable("A network error has occured or the path does not exist anymore");
}
}
}
else
{
if (myFolder.Exists)
{
_isNetworkUnavailable = false;
if (NetworkPathAvailable != null)
{
NetworkPathAvailable("The network or path has been restored");
}
}
}
}
catch (Exception ex)
{
throw;
}
finally
{
myFolder = null;
}
}
}
Tags:使用 FileSystemWatcher 监控
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接