LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C#使用 FileSystemWatcher 监视文件系统更改

admin
2023年12月26日 23:2 本文热度 366

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

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

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

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

注意FileSystemWatcher.NotifyFilter 属性设置的监视和事件(OnChangedOnCreatedOnDelete等事件)是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;

        // 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);
    }
}


该文章在 2023/12/26 23:02:00 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved