gpt4 book ai didi

.net - 在 Linux 世界中是否有等同于 .Net FileSystemWatcher 的东西?

转载 作者:IT王子 更新时间:2023-10-29 00:15:30 25 4
gpt4 key购买 nike

我发现 .Net FileSystemWatcher 类对于编写实用程序非常方便,这些实用程序会在文件出现在其监视的文件夹中时自动激活。在 *nix 世界中是否有任何等效于此功能的功能可以让我监视一个文件夹(可能还有它的所有子目录)?

编辑:最好是不需要内核补丁的东西。

最佳答案

我想分享我在 Ubuntu 10.10 的 Mono 中使用 FileSystemWatcher 的观察结果。这是 C# 中 FileSystemWatcher 的一个非常简单的实现

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using System.Reflection;

namespace FileSystemWatcherSandbox
{
public class Program
{
static void Main(string[] args)
{
foreach(DictionaryEntry de in Environment.GetEnvironmentVariables())
{
Console.WriteLine("{0} = {1}",de.Key,de.Value);
}
string basePath = AppDomain.CurrentDomain.BaseDirectory;
Console.WriteLine("watching: {0}", basePath);
FileSystemWatcher fsw = new FileSystemWatcher(basePath);
fsw.Changed += new FileSystemEventHandler(fsw_Changed);
fsw.Created += new FileSystemEventHandler(fsw_Created);
fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);
fsw.Error += new ErrorEventHandler(fsw_Error);
fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
fsw.EnableRaisingEvents = true;
fsw.IncludeSubdirectories = true;
while (true)
{
WaitForChangedResult result = fsw.WaitForChanged(WatcherChangeTypes.All,10000);
Console.WriteLine(result.TimedOut ? "Time out" : "hmmm");
}
}

static void fsw_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine("({0}): {1} | {2}", MethodInfo.GetCurrentMethod().Name, e.ChangeType, e.FullPath);
}

static void fsw_Error(object sender, ErrorEventArgs e)
{
Console.WriteLine("({0}): {1}", MethodInfo.GetCurrentMethod().Name, e.GetException().Message);
}

static void fsw_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine("({0}): {1} | {2}", MethodInfo.GetCurrentMethod().Name, e.ChangeType, e.FullPath);
}

static void fsw_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("({0}): {1} | {2}", MethodInfo.GetCurrentMethod().Name, e.ChangeType, e.FullPath);
}

static void fsw_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("({0}): {1} | {2}", MethodInfo.GetCurrentMethod().Name, e.ChangeType, e.FullPath);
}
}
}

此代码已经过测试,适用于 Windows XP 和 Ubuntu 10.10。但是,我想指出的是,在 Ubuntu 10.10(也可能是更早的版本)下,FileSystemWatcher 的行为是独一无二的。
如果正在监视的目录不包含子目录,则调用 IncludeSubdirectories 属性设置为 true 的 FileSystemWatcher 将导致 FileSystemWatcher 忽略事件。但是,如果目标目录中有子目录,则将 IncludeSubdirectories 设置为 true 将按预期工作。
如果将 IncludeSubdirectories 设置为 false,则始终有效。在这种情况下,FileSystemWatcher 将只监视目标目录。
我希望这对想要跨不同操作系统使用 Mono 并调用 FileSystemWatcher 类型的程序员有用。

关于.net - 在 Linux 世界中是否有等同于 .Net FileSystemWatcher 的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/324258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com