FileSystemWatcher类监控文件的更改状态并且实时备份文件

时间:2022-06-22 15:36:32

首先这是我自己在一个任务需求里面所要用到的,大致的代码如下:我把监视文件和备份文件的方法封装到一个WatcherAndBackup

类中了,但是总感觉封装的不是很好,有大牛能够指出改正之处在此留言,谢谢指点了哈!!,主要监视文件用到的类就是在sysytem.IO

里面的FileSystemWatcher,然后在一个控制台里面创建类WatcherAndBackup的实例并且运行就行

  class WatcherAndBackup
{
string sourcefile = "";//源文件
string targetfile = "";//目标文件
string targetPath = "";//目标路径
public WatcherAndBackup(string Sourcefile,string Targetfile,string TargetPath)
{
sourcefile = Sourcefile;targetfile = Targetfile;targetPath = TargetPath;
} public void backup(string sourcefile,string targetfile,string targetPath)
{
try
{
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath); }
File.Copy(sourcefile, targetfile, true); }
catch { }
}
#region 实时监视文件更改并且备份文件
public void watcherfile(string path,string file)
{
FileSystemWatcher fsw = new FileSystemWatcher(path, file);
fsw.Changed += new FileSystemEventHandler(change_watcher);
fsw.Created += new FileSystemEventHandler(change_watcher);
fsw.Deleted += new FileSystemEventHandler(change_watcher);
fsw.Renamed += new RenamedEventHandler(rename_watcher);
fsw.EnableRaisingEvents = true;
Console.WriteLine("开始监视。。。。");
fsw.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName
| NotifyFilters.LastAccess | NotifyFilters.Security | NotifyFilters.Size | NotifyFilters.LastWrite;
fsw.IncludeSubdirectories = true;
}
public void change_watcher(object sender,FileSystemEventArgs e)
{ var wacher = sender as FileSystemWatcher;
wacher.EnableRaisingEvents = false; if (e.ChangeType==WatcherChangeTypes.Changed)
{
Console.WriteLine("正在备份。。。");
backup(sourcefile,targetfile,targetPath);
Console.WriteLine("备份成功。。。"); }
else if (e.ChangeType==WatcherChangeTypes.Created)
{
Console.WriteLine("{0},{1},{2}", e.ChangeType, e.FullPath, e.Name);
return;
}
else if (e.ChangeType==WatcherChangeTypes.Deleted)
{
Console.WriteLine("{0},{1},{2}", e.ChangeType, e.FullPath, e.Name);
return;
}
wacher.EnableRaisingEvents = true;
}
public void rename_watcher(object sender,RenamedEventArgs e)
{
Console.WriteLine("{0},{1},{2}", e.ChangeType, e.FullPath, e.Name);
}
#endregion }
 static void Main(string[] args)
{
WatcherAndBackup bk = new WatcherAndBackup(@"D:\gg\config.xml", @"D:\gg\backup\config.xml", @"D:\gg\backup");
bk.watcherfile(@"D:\gg", "config.xml");//监视的文件为D:\gg\config.xml
Console.Read();
}

 在这里解释一下:实例类WatcherAndBackup时分别要写下backup方法的三个参数:sourcefile、targefile、targePath,也就是备份方法的源文件、目标文件、目标文件的目录,然后在change_watcher方法当中为什么会有这几局代码:

var wacher=sender as FileSystemWatcher;

wacher.EnableRaisingEvents=false;

然后在方法后面:

wacher.EnableRaisingEvents=true;

其实如果不加入这几句代码会出现当监控到文件修改时会触发两次changed方法,这个修改方法是我在网上找到的一个修改方法

好了,基本也说完了。。。有什么不正确的地方请各位大牛指正,本就打着学习的态度写下的。。嘿嘿!!


            
FileSystemWatcher类监控文件的更改状态并且实时备份文件