解决fileSystemWatcher的onChanged的事件触发多次的问题

Q:

FileSystemWatcher 的Changed事件,在我保存某个文本文件的时候,该事件可能会被出发多次,如何使他触发一次?

 

A:

解决fileSystemWatcher的onChanged的事件触发多次的WorkAround方法就是尝试在监视的文件或文件夹发生变化时通知Framework, 具体的代码如下:

 

My best guess is the FileWatcher fires the Create event once the file is opened for 
write and then again when it completes. I've added a test for file existence in the 
Event Handler and it does indeed FAIL on the first callback. The code below produced
 a series of debug prints showing every other callback has the OS reporting the file
 exists, i.e., 2,4,6,...


namespace MyExample
{
    class Program
    {
        private static FileSystemWatcher watcher;
        private static string mailbox = @"c:\Mailbox";
        private static int callbacks = 0;

        static void Main(string[] args)
        {
            watcher = new FileSystemWatcher();
            watcher.Path = mailbox;
            watcher.NotifyFilter = NotifyFilters.FileName;
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.EnableRaisingEvents = true;
        

            Console.WriteLine("Press Enter to quit\r\n");
            Console.ReadLine();    
        }



        public static void OnChanged(object source, FileSystemEventArgs e)
        {
            try
            {
                watcher.EnableRaisingEvents = false;
                callbacks++;
                FileInfo objFileInfo = new FileInfo(e.FullPath);
                if (!objFileInfo.Exists) return;   
// ignore the file open, wait for complete write
                ProcessAllFiles(e.FullPath);

            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                // do something?
            }
            finally
            {
                watcher.EnableRaisingEvents = true;
            }
        }




        public static void ProcessAllFiles(string FullPath)
        {
            // stub

	    string directory = FullPath.Substring(0, FullPath.LastIndexOf(@"\"));
            string filename = FullPath.Substring(FullPath.LastIndexOf(@"\"));
            Console.WriteLine("file: {0} Callback # {1} ", filename, callbacks);  
        }

 

关于解决fileSystemWatcher的onChanged的事件触发多次的WorkAround方法的详细信息,请参考下述文章:http://www.codeproject.com/useritems/FileWatcher.asp
此条目发表在article分类目录。将固定链接加入收藏夹。