这边使用EnableRaisingEvents属性来屏蔽在复制时候出现二次拷贝的现象。
public static string sourceTxtPath = "";
public static string sourceDbfPath = "";
public static string destinationTxtPath = "";
public static string destinationDbfPath = "";
public static System.IO.FileSystemWatcher Txtfsw = new System.IO.FileSystemWatcher();
public static System.IO.FileSystemWatcher Dbffsw = new System.IO.FileSystemWatcher();
static void Main(string[] args)
{
//sourceTxtPath = PinvokeRef.GetValueByKey("AppName", "sourceTxtPath");
//sourceDbfPath = PinvokeRef.GetValueByKey("AppName", "sourceDbfPath");
//destinationPath = PinvokeRef.GetValueByKey("AppName", "destinationPath");
try
{
sourceTxtPath = "z:\\";
sourceDbfPath = "y:\\";
destinationTxtPath = "C:\\hq\\mktdt73.txt";
destinationDbfPath = "C:\\hq\\show2003.dbf";
Txtfsw.Changed += new System.IO.FileSystemEventHandler(OnTxtChanged);
Txtfsw.Path = sourceTxtPath;
Txtfsw.Filter = "mktdt73.txt";
Txtfsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
Txtfsw.EnableRaisingEvents = true;
Dbffsw.Changed += new System.IO.FileSystemEventHandler(OnDbfChanged);
Dbffsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
Dbffsw.Path = sourceDbfPath;
Dbffsw.Filter = "show2003.dbf";
Dbffsw.EnableRaisingEvents = true;
System.Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString()+ex.Message.ToString());
Logger.Info("try catch error mesage:" + ex.ToString() + ex.Message.ToString());
}
}
protected static void OnTxtChanged(object source, FileSystemEventArgs e)
{
try {
Txtfsw.EnableRaisingEvents = false;
File.Copy(sourceTxtPath + "\\mktdt73.txt", destinationTxtPath, true);
Console.WriteLine("copy file mktdt73.txt sucess "+System.DateTime.Now);
Logger.Info("copy file mktdt73.txt sucess " + System.DateTime.Now);
}
catch (System.IO.IOException ext)
{
Console.WriteLine(ext.Message);
}
finally
{
Txtfsw.EnableRaisingEvents = true;//文件被还原后,再次启动监控
}
}
protected static void OnDbfChanged(object source, FileSystemEventArgs e)
{
try
{
Dbffsw.EnableRaisingEvents = false;
File.Copy(sourceDbfPath + "\\show2003.dbf", destinationDbfPath, true);
Console.WriteLine("copy file show2003.dbf sucess "+ System.DateTime.Now);
Logger.Info("copy file show2003.dbf sucess " + System.DateTime.Now);
}
catch (System.IO.IOException ext)
{
Console.WriteLine(ext.Message);
}
finally
{
Dbffsw.EnableRaisingEvents = true;//文件被还原后,再次启动监控
}
}
}