用于监听某个目录文件是否有创建文件或者修改文件,有则做一定处理。
using System.IO;
public partial class MainForm
{
/// <summary>
/// 目录监视器
/// </summary>
public FileSystemWatcher bFileSystemWatcher;
public static string ErrorMsg;
/// <summary>
/// 启动文件的监听服务
/// </summary>
public void StartBwWatcher()
{
if (bFileSystemWatcher!= null && BwFileSystemWatcher.EnableRaisingEvents)
{
return;
}
bFileSystemWatcher= new FileSystemWatcher
{
Path = BwHelper.GetTaxAppInstallPath() + "//SignLog//",
Filter = "*.*",
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.FileName
};
bFileSystemWatcher.Created += OnBillCreated;
bFileSystemWatcher.EnableRaisingEvents = true;
}
private void OnBillCreated(object source, FileSystemEventArgs e)
{
try
{
Thread.Sleep(100);
string fileName = e.Name.Substring(e.Name.IndexOf('\\') + 1);
if (!fileName.Contains("verifysign") || fileName.StartsWith("009", StringComparison.Ordinal))
{
return;
}
GetData(e); //读取文件内容方法
}
catch (IOException exception)
{
Log.Error("传输数据出现错误:" + exception.Message);
GetData(e);
}
catch (Exception ex)
{
Log.Error("传输数据出现错误:" + ex.Message);
}
}
//退出窗体关闭服务
bFileSystemWatcher.EnableRaisingEvents = false;
bFileSystemWatcher.Dispose();