您现在的位置: 365建站网 > 365文章 > c#中FileSystemWatcher监听文件是否有被修改或是否文件复制完成

c#中FileSystemWatcher监听文件是否有被修改或是否文件复制完成

文章来源:365jz.com     点击数:2125    更新时间:2018-06-07 11:00   参与评论

使用 FileSystemWatcher 监视指定目录中的更改。可监视指定目录中的文件或子目录的更改。该组件可以监视本地计算机、网络驱动器或远程计算机上的文件。

可监视目录或文件中的若干种更改。例如,可监视文件或目录的 Attributes、LastWrite 日期和时间或 Size 方面的更改。通过设置FileSystemWatcher.NotifyFilter属性。

可监视文件或目录的重命名、删除或创建。例如,若要监视文本文件的重命名,请将 Filter 属性设置为“*.txt”。注意   公共文件系统操作可能会引发多个事件。例如,将文件从一个目录移到另一个目录时,可能会引发若干 OnChanged 以及一些 OnCreated 和 OnDelete事件。移动文件是一个包含多个简单操作的复杂操作,因此会引发多个事件。同样,一些应用程序(如反病毒软件)可能导致被 FileSystemWatcher 检测到的附加文件系统事件。

注意FileSystemWatcher.NotifyFilter 属性设置的监视和事件(OnChanged,OnCreated,OnDelete等事件)是and的关系。

例子程序:

</>code

  1. public class Watcher 
  2. {
  3.     public static void Main() 
  4.     {
  5.         string[] args = System.Environment.GetCommandLineArgs(); 
  6.   
  7.         // If a directory is not specified, exit program. 
  8.         if(args.Length != 2) 
  9.         { 
  10.             // Display the proper way to call the program. 
  11.             Console.WriteLine("Usage: Watcher.exe (directory)"); 
  12.             return; 
  13.         }
  14.         // Create a new FileSystemWatcher and set its properties. 
  15.         FileSystemWatcher watcher = new FileSystemWatcher(); 
  16.         watcher.Path = args[1]; 
  17.         /* Watch for changes in LastAccess and LastWrite times, and 
  18.            the renaming of files or directories. */ 
  19.         watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite 
  20.            | NotifyFilters.FileName | NotifyFilters.DirectoryName; 
  21.         // Only watch text files. 
  22.         watcher.Filter = "*.txt";
  23.         // Add event handlers. 
  24.         watcher.Changed += new FileSystemEventHandler(OnChanged); 
  25.         watcher.Created += new FileSystemEventHandler(OnChanged); 
  26.         watcher.Deleted += new FileSystemEventHandler(OnChanged); 
  27.         watcher.Renamed += new RenamedEventHandler(OnRenamed);
  28.         // Begin watching. 
  29.         watcher.EnableRaisingEvents = true; 
  30.  //Suspend the calling thread until the file has been created
  31.             WaitForChangedResult cr= watcher.WaitForChanged(WatcherChangeTypes.Created);
  32.         // Wait for the user to quit the program. 
  33.         Console.WriteLine("Press /'q/' to quit the sample."); 
  34.         while(Console.Read()!='q'); 
  35.     }
  36.     // Define the event handlers. 
  37.     private static void OnChanged(object source, FileSystemEventArgs e) 
  38.     {
  39.         // Specify what is done when a file is changed, created, or deleted. 
  40.        Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType); 
  41.     }
  42.     private static void OnRenamed(object source, RenamedEventArgs e) 
  43.     { 
  44.         // Specify what is done when a file is renamed. 
  45.         Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath); 
  46.     } 
  47. }


 

 

但是,在实际使用过程中,由于需要监视的文件,必须在复制完成后才能进行后续工作,所以在监视时,需要不断进行判断,判断文件是否复制完成。所以修改

</>code

  1.        private static void OnChanged(object source, FileSystemEventArgs e)
  2.         {
  3.             // Specify what is done when a file is changed, created, or deleted.
  4.             Console.WriteLine("File: "  + " " + e.ChangeType);
  5.             string filepath = e.FullPath; //mypath + "//" + cr.Name;
  6.             FileInfo fi = new FileInfo(filepath);
  7.             if (!fi.Exists)
  8.             {
  9.                 Console.WriteLine("file not exits!!");
  10.             }
  11.             Console.WriteLine(fi.IsReadOnly.ToString());
  12.             //if (!fi.IsReadOnly)
  13.             //{
  14.             //    fi.AppendText();
  15.             //}
  16.  HELLO:           try
  17.             {
  18.                 fi.OpenRead();
  19.             }
  20.             catch (IOException  ex)
  21.             {
  22.                 Console.WriteLine(ex.Message);
  23.                 
  24.                 Thread.Sleep(3000);
  25.                 goto HELLO;
  26.                 
  27.             
  28.             }
  29.             OnRMChanged(e.FullPath);//对文件进行任意处理
  30.             
  31.         }

最后等复制完成再对文件进行操作如下

</>code

  1. private static void OnRMChanged(string mypath)
  2. {
  3. //对文件进行任意处理
  4. }

根据该文章改造成我自己的文件监控器,哈哈


FileSystemWatcher监听文件是否有被修改


作用:监听文件系统更改通知,并在目录或目录中的文件更改时引发事件。

 

需求:监听特定文件是否修改,然后做出相应的操作。

方法:

①利用一个线程,一直去查找该指定的文件是否有被修改,如果修改则操作特定步骤,否则继续查询。

缺点:占用CPU,要一直循环查找。

②利用.net里面的FileSystemWatcher来监听文件是否有被修改,如果有,则操作特定步骤。

 

代码:

①定义一个全局变量Watch

</>code

  1. FileSystemWatcher Watch;

②初始化该全局变量

</>code

  1.            Watch = new FileSystemWatcher();
  2.             Watch.Path = @"C:\Users\RAPOO\Desktop\123";
  3.             Watch.Filter = "modlist.mod";
  4.             Watch.NotifyFilter = NotifyFilters.LastWrite;
  5.             Watch.IncludeSubdirectories = false;
  6.             Watch.Changed += new FileSystemEventHandler(watch_changed);
  7.             Watch.EnableRaisingEvents = true;

③相应修改事件

</>code

  1.        private void watch_changed(object source, FileSystemEventArgs e)
  2.         {            if (Watch != null)
  3.             {                try
  4.                 {
  5.                     Watch.EnableRaisingEvents = false;
  6.                     MessageBox.Show("改变!!!");
  7.                 }                finally
  8.                 {
  9.                     Watch.EnableRaisingEvents = true;
  10.                 }
  11.             }
  12.         }

注意:

1、代码只添加修改事件,还有重命名、删除、新增事件。

2、在修改事件里面,需要将事件监控先重置为false,待执行结束后再修改为true。目的是解决修改事件执行两次的BUG。

下图为MSDN上注释。


如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (2125人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号