文件监控对象FileSystemWatcher使用感受
http://www.cnblogs.com/zhaojingjing/archive/2011/01/21/1941586.html
新做一个项目:要对文件夹进行监控,其实功能很简单,但我每次都给复杂化,所以至此耽误很多时间,那一刻突然明白,做为技术人员,重要的不是会你会什么技术,而是你如果有解决问题的能力其它一切都不在话下,加油吧。
这个项目运用到:FileSystemWatcher 对文件进行监控,如果文件有更改,就将文件复制到更一个文件夹下,
/// <summary> /// 指定文件夹下面的所有内容copy到目标文件夹下面 /// </summary> /// <param name="srcPath">原始路径</param> /// <param name="aimPath">目标文件夹</param> public static void CopyDir(string srcPath, string aimPath) { try { string[] strArr = srcPath.Split(new char[] { '\\' }); // 检查目标目录是否以目录分割字符结束如果不是则添加之 if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar) aimPath += Path.DirectorySeparatorChar; // 判断目标目录是否存在如果不存在则新建之 if (!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath); // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组 //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法 //string[] fileList = Directory.GetFiles(srcPath); // string[] fileList = Directory.GetFileSystemEntries(srcPath); //遍历所有的文件和目录 //foreach (string file in fileList) //{ // //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 // if (Directory.Exists(file)) // CopyDir(file, aimPath + Path.GetFileName(file)); //否则直接Copy文件 // else File.Copy(srcPath, aimPath + Path.GetFileName(DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + strArr[strArr.Length - 1]), true); // } } catch (Exception ee) { throw new Exception(ee.ToString()); } }
当对文件监控时,文件修改在打开过程中会出许多临时文件,例如:.temp 类似 ,这个在程序中用判断可以将其屏蔽掉,不作为记录。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.IO; //for fileSystemWatcher namespace FileEventWatcher { public partial class fileSystemWatcherFrm : Form { public fileSystemWatcherFrm() { InitializeComponent(); } private delegate void setLogTextDelegate(FileSystemEventArgs e); private delegate void renamedDelegate(RenamedEventArgs e); FileSystemWatcher[] fswArr; private void fileSystemWatcherFrm_Load(object sender, EventArgs e) { versionInfo_tsbtn.Visible = false; //隐藏 ListViewGroup hardDisk_lvg = new ListViewGroup(); hardDisk_lvg.Header = "可监控硬盘"; hardDisk_lvg.Name = "hardDisk"; ListViewGroup removableDisk_lvg = new ListViewGroup(); removableDisk_lvg.Header = "可监控移动硬盘"; removableDisk_lvg.Name = "removableDisk"; ListViewGroup other_lvg = new ListViewGroup(); other_lvg.Header = "其它"; other_lvg.Name = "other"; this.dir_lvw.Groups.Add(hardDisk_lvg); this.dir_lvw.Groups.Add(removableDisk_lvg); this.dir_lvw.Groups.Add(other_lvg); this.dir_lvw.ShowGroups = true; this.dir_lvw.LargeImageList = this.file_ilst; spcifiedFloder_rbtn.Checked = true; foreach (string driverName in Directory.GetLogicalDrives()) { DriveInfo driverInfo = new DriveInfo(driverName); if (driverInfo.IsReady == true) { if (driverInfo.DriveType == DriveType.Fixed) { ListViewItem lvi = new ListViewItem(); lvi.ImageIndex = 0; lvi.Text = driverInfo.Name; lvi.Group = hardDisk_lvg; this.dir_lvw.Items.Add(lvi); } else if (driverInfo.DriveType == DriveType.Removable) { ListViewItem lvi = new ListViewItem(); lvi.ImageIndex = 1; lvi.Text = driverInfo.Name; lvi.Group = removableDisk_lvg; this.dir_lvw.Items.Add(lvi); } } } this.dir_lvw.Items.Add(new ListViewItem("系统盘", 2, other_lvg)); } private void setLogText(FileSystemEventArgs e) { string[] strArr = e.FullPath.Split(new char[] { '\\' }); if (!strArr[1].Equals("$RECYCLE.BIN")) //回收站 { this.fileEventLog_lvw.BeginUpdate(); ListViewItem lvi = new ListViewItem(); lvi.SubItems.Add(DateTime.Now.ToString()); lvi.SubItems.Add(e.ChangeType.ToString()); lvi.SubItems.Add(strArr[0]); //硬盘 lvi.SubItems.Add(strArr[strArr.Length - 1]); //文件名 lvi.SubItems.Add(e.FullPath); switch (e.ChangeType) { case WatcherChangeTypes.Created: lvi.ForeColor = Color.Lime; lvi.SubItems.Add("在" + strArr[0] + "盘创建了【" + strArr[strArr.Length - 1] + "】"); break; case WatcherChangeTypes.Deleted: lvi.ForeColor = Color.Red; lvi.SubItems.Add("在" + strArr[0] + "盘删除了【" + strArr[strArr.Length - 1] + "】"); break; case WatcherChangeTypes.Changed: lvi.ForeColor = Color.Fuchsia; lvi.SubItems.Add("在" + strArr[0] + "盘修改了【" + strArr[strArr.Length - 1] + "】"); break; } this.fileEventLog_lvw.Items.Add(lvi); this.fileEventLog_lvw.EndUpdate(); } } private void setRenamedLogText(RenamedEventArgs e) { string[] oldStrArr = e.OldFullPath.Split(new char[] { '\\' }); string[] newStrArr = e.Name.Split(new char[] { '\\' }); ListViewItem lvi = new ListViewItem(); lvi.ForeColor = Color.Yellow; lvi.SubItems.Add(DateTime.Now.ToString()); lvi.SubItems.Add(e.ChangeType.ToString()); lvi.SubItems.Add(oldStrArr[0]); //硬盘 lvi.SubItems.Add(oldStrArr[oldStrArr.Length - 1] + " → " + newStrArr[newStrArr.Length - 1]); //文件名 lvi.SubItems.Add(e.FullPath); lvi.SubItems.Add("在" + oldStrArr[0] + "盘将【" + oldStrArr[oldStrArr.Length - 1] + "】重命名为 【" + newStrArr[newStrArr.Length - 1] + "】"); this.fileEventLog_lvw.Items.Add(lvi); } private void fileSystemWatcher_EventHandle(object sender, FileSystemEventArgs e) { string[] strPath = e.FullPath.Split(new char[] { '\\' }); if (e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Changed || e.ChangeType == WatcherChangeTypes.Deleted) { if (strPath[strPath.Length - 1].IndexOf("~$") < 0) { string strFileName = strPath[strPath.Length - 1]; //文件名 string[] strTempName = strFileName.Split(new char[] { '.' }); if (strTempName.Length > 1) { //if (strTempName[1] == "doc" || strTempName[1] == "docx" || strTempName[1] == "txt") //{ MoveFolderTo(e.FullPath, filePath_txt.Text); // } } } } if (this.fileEventLog_lvw.InvokeRequired) { this.fileEventLog_lvw.Invoke(new setLogTextDelegate(setLogText), new object[] { e }); } } private void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e) { if (this.fileEventLog_lvw.InvokeRequired) { this.fileEventLog_lvw.Invoke(new renamedDelegate(setRenamedLogText), new object[] { e }); } } private void stop_tsbtn_Click(object sender, EventArgs e) { foreach (FileSystemWatcher fsw in fswArr) { fsw.EnableRaisingEvents = false; //获取或设置一个值,该值指示是否启用此组件。 } this.stop_tsbtn.Enabled = false; this.start_tsbtn.Enabled = true; } private void start_tsbtn_Click(object sender, EventArgs e) { if (this.spcifiedFloder_rbtn.Checked) { if (!string.IsNullOrEmpty(this.filePath_txt.Text)) { fswArr = new FileSystemWatcher[1]; fswArr[0] = new FileSystemWatcher(); fswArr[0].Path = this.filePath_txt.Text; //设置监控路径 fswArr[0].IncludeSubdirectories = this.subDirWatcher_chk.Checked; //获取或设置一个值,该值指示是否监视指定路径中的子目录。 fswArr[0].NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size; fswArr[0].Created += new FileSystemEventHandler(this.fileSystemWatcher_EventHandle); fswArr[0].Deleted += new FileSystemEventHandler(this.fileSystemWatcher_EventHandle); fswArr[0].Changed += new FileSystemEventHandler(this.fileSystemWatcher_EventHandle); fswArr[0].Renamed += new RenamedEventHandler(this.fileSystemWatcher_Renamed); fswArr[0].EnableRaisingEvents = true; } else { MessageBox.Show("请先选择监控路径!"); return; } } else { int checkedCount = this.dir_lvw.CheckedItems.Count; if (checkedCount > 0) { fswArr = new FileSystemWatcher[checkedCount]; for (int i = 0; i < this.dir_lvw.CheckedItems.Count; i++) { fswArr[i] = new FileSystemWatcher(); fswArr[i].Path = this.dir_lvw.CheckedItems[i].Text; fswArr[i].IncludeSubdirectories = this.subDirWatcher_chk.Checked; //获取或设置一个值,该值指示是否监视指定路径中的子目录。 fswArr[i].NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size; fswArr[i].Created += new FileSystemEventHandler(this.fileSystemWatcher_EventHandle); fswArr[i].Deleted += new FileSystemEventHandler(this.fileSystemWatcher_EventHandle); fswArr[i].Changed += new FileSystemEventHandler(this.fileSystemWatcher_EventHandle); fswArr[i].Renamed += new RenamedEventHandler(this.fileSystemWatcher_Renamed); fswArr[i].EnableRaisingEvents = true; } } else { MessageBox.Show("您尚未选择任何监控路径!"); return; } } this.start_tsbtn.Enabled = false; this.stop_tsbtn.Enabled = true; } private void clear_tsbtn_Click(object sender, EventArgs e) { this.fileEventLog_lvw.Items.Clear(); } private void fileWatcherPath_btn_Click(object sender, EventArgs e) { FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.RootFolder = Environment.SpecialFolder.Desktop; fbd.Description = "请选择要监控的文件目录:"; if (fbd.ShowDialog() == DialogResult.OK) { this.filePath_txt.Text = fbd.SelectedPath; } } private void 打开目录ToolStripMenuItem_Click(object sender, EventArgs e) { if (this.fileEventLog_lvw.SelectedItems.Count > 0) { ListViewItem selectedItem = this.fileEventLog_lvw.SelectedItems[0]; if (selectedItem.SubItems[2].Text.Equals("Deleted")) { System.Diagnostics.Process.Start("explorer.exe", "/select," + selectedItem.SubItems[5].Text + "\\$RECYCLE.BIN\\回收站"); } else { System.Diagnostics.Process.Start("explorer.exe", "/select," + selectedItem.SubItems[5].Text); } } } private void dir_lvw_ItemCheck(object sender, ItemCheckEventArgs e) { if (this.dir_lvw.Items[e.Index].Group.Name.Equals("other")) { if (this.dir_lvw.Items[0].Checked) { MessageBox.Show("已选择C:盘监控"); e.NewValue = CheckState.Unchecked; } } } private void save_tsbtn_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.InitialDirectory = Application.StartupPath + "\\Logs"; sfd.RestoreDirectory = true; sfd.FileName = DateTime.Now.ToString("yyyyMMdd hh-mm-ss") + ".log"; if (sfd.ShowDialog() == DialogResult.OK) { StreamWriter sw = new StreamWriter(sfd.FileName); for (int i = 0; i < this.fileEventLog_lvw.Items.Count; i++) { string str = "[" + this.fileEventLog_lvw.Items[i].SubItems[1].Text + "]【" + this.fileEventLog_lvw.Items[i].SubItems[2].Text + "】[" + this.fileEventLog_lvw.Items[i].SubItems[3].Text + "][" + this.fileEventLog_lvw.Items[i].SubItems[4].Text + "][" + this.fileEventLog_lvw.Items[i].SubItems[5].Text + "][" + this.fileEventLog_lvw.Items[6].SubItems[4].Text + "]"; sw.WriteLine(str); } sw.Close(); } } private void allDisk_chk_CheckedChanged(object sender, EventArgs e) { if (this.allDisk_chk.Checked) { foreach (ListViewItem lvi in this.dir_lvw.Items) { if (lvi.Group.Name.Equals("hardDisk") || lvi.Group.Name.Equals("removableDisk")) { lvi.Checked = true; } } } else { foreach (ListViewItem lvi in this.dir_lvw.Items) { if (lvi.Group.Name.Equals("hardDisk") || lvi.Group.Name.Equals("removableDisk")) { lvi.Checked = false; } } } } //File.Copy(源文件地址,目标地址, true(为true是覆盖同名文件)); /// <summary> /// 从一个目录将其内容移动到另一目录 /// </summary> /// <param name="p">源目录</param> /// <param name="p_2">目的目录</param> private void MoveFolderTo(string p, string p_2) { //检查是否存在目的目录 //string[] strArr = p.Split(new char[] { '\\' }); //string HardDisk = strArr[0]; //硬盘 //string FileName = strArr[strArr.Length - 1]; //文件名 //String sourcePath = p; //String targetPath = p_2; //string[] strTempName = FileName.Split(new char[] { '.' }); //string strName = strTempName[0] + "_" + DateTime.Now.ToString("yyyyMMddhhmmss") + "." + strTempName[1]; if (File.Exists(p)) { string[] strPath = p.Split(new char[] { '\\' }); if (strPath[strPath.Length - 1].IndexOf("~$") < 0) { CopyDir(p, "D:\\Rourse\\服务器数据备份"); //Object Nothing = System.Reflection.Missing.Value; ////创建一个名为WordApp的组件对象 //Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); //object filename = p; ////创建一个名为WordDoc的文档对象并打开 //Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); ////设置保存的格式 //object savefilename = "D:/Rourse/服务器数据备份/" + strName; //object filefarmat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault; //doc.SaveAs(ref savefilename, ref filefarmat, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); //doc.Close(ref Nothing, ref Nothing, ref Nothing); ////推出组建 //wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); } } } /// <summary> /// 双击任务栏图标时,还原窗口 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { //if (this.WindowState == FormWindowState.Minimized) // this.WindowState = FormWindowState.Normal; //this.Activate(); //this.notifyIcon1.Visible = false; if (e.Button == MouseButtons.Right) { contextMenuStrip1.Show(); } if (e.Button == MouseButtons.Left) { this.Visible = true; this.WindowState = FormWindowState.Normal; } } ///// <summary> ///// 添加窗体最小化事件 ///// </summary> ///// <param name="sender"></param> ///// <param name="e"></param> //private void fileSystemWatcherFrm_SizeChanged(object sender, EventArgs e) //{ // //if (this.WindowState == FormWindowState.Minimized)//最小化 // //{ // // this.ShowInTaskbar = false; // // this.notifyIcon1.Visible = true; // //} // if (this.WindowState == FormWindowState.Normal && this.Visible == true) // { // this.notifyIcon1.Visible = true;//在通知区显示Form的Icon // this.WindowState = FormWindowState.Minimized; // this.Visible = false; // this.ShowInTaskbar = false;//使Form不在任务栏上显示 // } //} private void contextMenuStrip1_Click(object sender, EventArgs e) { Application.Exit(); } private void fileSystemWatcherFrm_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing)//当用户点击窗体右上角X按钮或(Alt + F4)时 发生 { e.Cancel = true; this.ShowInTaskbar = false; this.notifyIcon1.Icon = this.Icon; this.Hide(); } } private void toolStripButton1_Click(object sender, EventArgs e) { if (MessageBox.Show("确定要退出吗?") == DialogResult.OK) { Application.Exit(); } } #region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。 /**************************************** * 函数名称:CopyDir * 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。 * 参 数:srcPath:原始路径,aimPath:目标文件夹 * 调用示列: * string srcPath = Server.MapPath( "test/"); * string aimPath = Server.MapPath( "test1/"); * EC.FileObj.CopyDir(srcPath,aimPath); *****************************************/ /// <summary> /// 指定文件夹下面的所有内容copy到目标文件夹下面 /// </summary> /// <param name="srcPath">原始路径</param> /// <param name="aimPath">目标文件夹</param> public static void CopyDir(string srcPath, string aimPath) { try { string[] strArr = srcPath.Split(new char[] { '\\' }); // 检查目标目录是否以目录分割字符结束如果不是则添加之 if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar) aimPath += Path.DirectorySeparatorChar; // 判断目标目录是否存在如果不存在则新建之 if (!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath); // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组 //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法 //string[] fileList = Directory.GetFiles(srcPath); // string[] fileList = Directory.GetFileSystemEntries(srcPath); //遍历所有的文件和目录 //foreach (string file in fileList) //{ // //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 // if (Directory.Exists(file)) // CopyDir(file, aimPath + Path.GetFileName(file)); //否则直接Copy文件 // else File.Copy(srcPath, aimPath + Path.GetFileName(DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + strArr[strArr.Length - 1]), true); // } } catch (Exception ee) { throw new Exception(ee.ToString()); } } #endregion } }
一点一滴 坚持,汇成知识的海洋~ 希望自己能进步!