65.9K
CodeProject 正在变化。 阅读更多。
Home

智能监视器

starIconstarIconstarIconstarIconstarIcon

5.00/5 (19投票s)

2013 年 1 月 13 日

BSD

5分钟阅读

viewsIcon

61025

downloadIcon

1930

易于使用的目录监视工具。

介绍  

注意:Smartwatcher 现在托管在 CodePlex 上,您可以在以下网址下载代码并查看更新:

https://smartwatcher.codeplex.com/ 

Smart Watcher 是一款简单的 Windows 服务,旨在监视特定目录并在这些目录中对文件事件(创建、更改、重命名、删除)采取特定操作。此工具的优势在于

  • 支持插件,只需编写您的业务逻辑(您想对文件执行的操作),将代码编译成 DLL,然后让 Smart Watcher 负责文件监视。
  • 检查文件是否被其他服务占用,并在处理之前等待(在处理大文件或下载文件时非常有用)。
  • 支持多种文件扩展名和筛选器。
  • 使用正则表达式进行文件筛选。- 同时监视多个目录。
  • 在许多文件同时创建时创建队列。
  • 在成功或失败的情况下将文件归档为受密码保护的 zip 文件。

使用该工具  

要使用 Smart Watcher,您只需安装服务并开发您的插件,然后将它们添加到服务根目录下的插件文件夹中。要安装服务,只需双击服务可执行文件(感谢 Sudheer Reddy Battula 的文章:安装 .NET Windows 服务(最简单的方法))。在启动服务之前,您应该在 exe 配置文件中设置 SuccessArchivePath 和 FailureArchivePath 设置,以告诉服务您希望在哪里将文件的压缩副本归档到处理之后。此外,设置中的 'ReadTries' 决定了在文件被其他服务使用时,服务应尝试访问文件的次数,如果下载大文件,您应该增加此值。要创建插件,请创建一个新的类库项目,并将您的类继承自 IPlugin 接口,并处理接口属性和方法。

string Name { get; set; }
string WatchPath { get; set; }
string Filter { get; set; }
bool CatchAllFiles { get; set; }
string ZipPassword { get; set; }
string FilePrefix { get; set; }
IPluginHost Host { get; set; }
bool ArchiveFiles { get; set; }
bool DeleteFiles { get; set; }

/// <summary>
/// Event occurs when the a File or Directory is created
/// </summary>
/// <param name="fileName">The file full path name</param>
/// <returns></returns>
bool FileCreated(string fileName);
/// <summary>
/// Event occurs when the contents of a File or Directory are changed
/// </summary>
/// <param name="fileName">The file full path name</param>
/// <returns></returns>
bool FileChanged(string fileName);
/// <summary>
/// Event occurs when the a File or Directory is deleted
/// </summary>
/// <param name="fileName">The file full path name</param>
/// <returns></returns>
bool FileDeleted(string fileName);
/// <summary>
/// Event occurs when the a File or Directory is renamed
/// </summary>
/// <param name="fileName">The file full path name</param>
/// <returns></returns>
bool FileRenamed(string fileName); 

Name:您的插件的名称。
WatchPath:服务要监视的目录路径。
Filter:用于确定目录中监视哪些文件的筛选器字符串。
ZipPassword:归档时创建的 zip 文件的密码。
FilePrefix:添加到归档的 zip 文件名称的 것입니다。
ArchiveFiles:如果为 True,则让服务通过 zip 压缩并保存到指定文件夹来归档文件。
DeleteFiles:如果为 True,则在完成处理后删除文件。
编译您的库,然后将程序集文件扩展名从 'dll' 更改为 '.plug'。
将程序集复制到 Smart Watcher bin 文件夹中的 'Plugin' 文件夹。
最后启动服务。

深入了解  

通过安装服务和编写插件,您只是触及了表面。让我们深入了解一下
Smart Watcher 的工作原理,首先让我用另一种方式重新定义 Smart Watcher
Smart Watch 是一个封装了 FileSystemWatcher 类的 Windows 服务,它是一个可插拔的服务,所以您可以
编写您的插件,每个插件都可以关联到监视一个特定的文件夹,并带有特定的文件筛选器。
每添加一个插件,Smart Watcher 都会自动创建一个 FileSystemWatcher 实例并将其添加到服务的监视器列表中。服务将负责其他所有事情,包括内置的队列系统,以避免在许多文件同时创建或更改时发生任何问题,它还会在将文件发送到相应的插件之前检查文件是否可用且未被另一个应用程序使用。

变量

#region Variables
// Failur archive folder path from service setting
public static string SettingsFailureArchivePath = Properties.Settings.Default.FailureArchivePath;
// Success archive folder path from service setting
public static string SettingsSuccessArchivePath = Properties.Settings.Default.SuccessArchivePath;
// How many tries to access the file in case it used by another service
public static int SettingsReadTries = Properties.Settings.Default.ReadTries;
// the extention of zipped archived files
public static string SettingsZipFileExtention = "zip";
// the path of plugin folder (where the Smart Watcher will look for its plugins)
private readonly string _PluginFolder = AppDomain.CurrentDomain.BaseDirectory + @"Plugin\";

// a list of the avilable plugins into Plugin folder
public static IPlugin[] ipi;

// List of file watchers (the Smart Watcher create one for each plugin)
private List<FileSystemWatcher> _lstWatchers = new List<FileSystemWatcher>();

// FileProcessor is the class which maintains a queue of files to be processed and controls a worker thread which processes each file in the queue.
static FileProcessor processor;

#endregion  

方法:  

#region Methods

// this function is responsible a about looking for plugins
// into Plugin folder and add them the Smart Wacher plugins list (ipi)
private void LoadPlugIns()

// After Smart Watcher detect its plugins it call this function to create
// a SystemFileWatcher for each plugin and initialize it with plugin sttings.
private void RegisterWatchers()

#endregion

构造函数

在服务构造函数中,我们首先创建一个 FileProcessor 类的实例来维护文件队列,然后调用 LoadPlugin 方法来检查可用的插件,然后调用 RegisterWatchers 函数来创建监视器列表。

注意:System.Diagnostics.Debugger.Launch(); 行用于调试服务,更多详情请查看此 URL

public SmartWatcherService()
{
    InitializeComponent();

    #if DEBUG
        System.Diagnostics.Debugger.Launch();
    #endif

        // intilaize files processor to maintains files queue 
        processor = new FileProcessor();

        LoadPlugIns();
        RegisterWatchers();
}

事件

服务中有四个主要的文件事件

  • fswWatcher_Changed:文件或目录的内容发生更改时发生的事件。
  • fswWatcher_Created:文件或目录被创建时发生的事件。
  • fswWatcher_Deleted:文件或目录被删除时发生的事件。
  • fswWatcher_Renamed:文件或目录被重命名时发生的事件。

这些事件中的每一个被触发时都会调用函数 processor.QueueInput(e.FullPath, e.ChangeType); 其中“e.FullPath”是文件名,“e.ChangeType”是事件的类型。QueueInput 函数将文件添加到队列中,并等待其处理顺序。当文件准备好时,将调用两个重要函数。

private void ProcessFile(string fileInfo)
{
    string[] file = fileInfo.Split('|');
    WatcherChangeTypes changeType;
    WatcherChangeTypes.TryParse(file[0], true, out changeType);
    string filepath = file[1];
    

    if (!File.Exists(filepath))
    {
        //ToDo: Add Handle Exception
        return;
    }

    // Check if file is accessble
    if (!WaitReady(filepath, SmartWatcherService.SettingsReadTries))
    {
        //ToDo: Add Log
        return;
    }

    foreach (IPlugin t in SmartWatcherService.ipi)
    {
        string strFiletr = t.Filter.Replace("*", @"\\*");
        Match match = Regex.Match(Path.GetFileName(filepath), strFiletr);
        if (match.Success == true)
        {
            Func<string, bool> pluginFunc = null;
            switch (changeType)
            {
                    case WatcherChangeTypes.Created:
                    {
                        pluginFunc = t.FileCreated;
                        break;
                    }
                    case WatcherChangeTypes.Changed:
                    {
                        pluginFunc = t.FileChanged;
                        break;
                    }
                    case WatcherChangeTypes.Renamed:
                    {
                        pluginFunc = t.FileRenamed;
                        break;
                    }
                    case WatcherChangeTypes.Deleted:
                    {
                        pluginFunc = t.FileDeleted;
                        break;
                    }
            }

            ProcessPluginAction(pluginFunc, filepath, t.ArchiveFiles, t.DeleteFiles, t.FilePrefix,
                                t.ZipPassword);
        }
    }
}  

ProcessFile 函数使用 Regex 查找哪个插件的筛选器适用于此文件(因此,如果筛选器适用,则一个文件可以被多个插件处理),对于每个适用的插件,它都会调用“ProcessPluginAction”函数。

private void ProcessPluginAction(Func<string, bool> pluginMethod, string fileFullName, bool archiveFiles, bool deleteFiles, string filePrefix, string zipPassword)
{

    string strArchivePath = SmartWatcherService.SettingsFailureArchivePath;
    try
    {
        pluginMethod(fileFullName);
        strArchivePath = SmartWatcherService.SettingsSuccessArchivePath;

    }
    catch (Exception ex)
    {
        //ToDo: add exception handeling                  
    }
    finally
    {
        if (archiveFiles == true)
        {
            string strArchiveFileName = filePrefix + "_" + DateTime.Now.ToString("yyyyMMddHHmmssss") + "_" +
                                        Path.GetFileName(fileFullName) + "." + SmartWatcherService.SettingsZipFileExtention;
            ZipUtil.ZipFile(fileFullName, strArchivePath + strArchiveFileName, zipPassword);
        }
        if (deleteFiles == true)
        {
            if (File.Exists(fileFullName))
            {
                // Check if file is accessble
                if (FileProcessor.WaitReady(fileFullName, SmartWatcherService.SettingsReadTries) == true)
                {
                    File.Delete(fileFullName);
                }
            }
        }
    }

}  

ProcessPluginAction 函数接受代表应从插件调用的方法的 Func 委托参数,并将文件名传递给该方法。此外,其他参数作为标志,用于在完成后归档(zip)或删除文件。

值得关注的点  

Smart Watcher 是一个易于使用的工具,可以帮助您自动化许多任务,它可以通过开发许多插件来执行各种操作,例如:发送邮件、打印文档、传输文件、启动程序等。
我可以将其与一些商业解决方案进行比较,例如:WatchDirectory
对于文件 zip 压缩,我正在使用开源库: SharpZipLib 

历史   

2013/1/13 初始发布 0.1 

2013/08/06 项目已作为 SmartWatcher 添加到 CodePlex。

2013/09/05 SmartWatcher 1.3.0.0 已发布。您可以在此处查看发布说明并获取其源代码: SmartWatcher 1.3.0.0 

发布说明

- 添加:引入 SmartTimer:一个实现定时器的功能,该定时器以用户定义的间隔引发事件。现在 SmartWatcher 支持 Tick 事件
定期调用代码。每隔几秒或几分钟,只需在您的插件中处理此事件,SmartWatcher 就会调用您的代码。

- 添加:引入 SmartActions:一个将包含代码片段和函数的库,以便您可以直接在 SmartWatcher 插件中使用它们。

- 添加:SmartWatcher 项目的 PluginsLibrary 文件夹,用于添加未来的插件。 

 

 

 

 

© . All rights reserved.