使用 FileSystemWatcher 监视文件系统更改 [转]

      FD程序开发 2007-11-7 16:56

使用 FileSystemWatcher 监视文件系统更改   

该文章摘自msdn中System.IO.FileSystemWatcher的介绍。

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

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

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

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

例子程序:

public class Watcher
{

    public static void Main()
    {

        string[] args = System.Environment.GetCommandLineArgs();
 
        // If a directory is not specified, exit program.
        if(args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");
            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = args[1];
        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        // Only watch text files.
        watcher.Filter = "*.txt";

        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Begin watching.
        watcher.EnableRaisingEvents = true;
 //Suspend the calling thread until the file has been created
            WaitForChangedResult cr= watcher.WaitForChanged(WatcherChangeTypes.Created);
        // Wait for the user to quit the program.
        Console.WriteLine("Press \'q\' to quit the sample.");
        while(Console.Read()!='q');
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {


        // Specify what is done when a file is changed, created, or deleted.
       Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        // Specify what is done when a file is renamed.
        Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
    }
}
 

 

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

       private static void OnChanged(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted.
            Console.WriteLine("File: "  + " " + e.ChangeType);

            string filepath = e.FullPath; //mypath + "\\" + cr.Name;
            FileInfo fi = new FileInfo(filepath);

            if (!fi.Exists)
            {

                Console.WriteLine("file not exits!!");

            }
            Console.WriteLine(fi.IsReadOnly.ToString());
            //if (!fi.IsReadOnly)
            //{

            //    fi.AppendText();
            //}
 HELLO:           try
            {

                fi.OpenRead();
            }
            catch (IOException  ex)
            {

                Console.WriteLine(ex.Message);
                
                Thread.Sleep(3000);
                goto HELLO;
               
           
            }
            OnRMChanged(e.FullPath);//对文件进行任意处理
            
        }

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

private static void OnRMChanged(string mypath)

{

//对文件进行任意处理

}

 

回复Comments() 点击Count()

回复Comments

{commentauthor}
{commentauthor}
{commenttime}
{commentnum}
{commentcontent}
作者:
{commentrecontent}