WatchFile.Core
2.3.1
See the version list below for details.
dotnet add package WatchFile.Core --version 2.3.1
NuGet\Install-Package WatchFile.Core -Version 2.3.1
<PackageReference Include="WatchFile.Core" Version="2.3.1" />
<PackageVersion Include="WatchFile.Core" Version="2.3.1" />
<PackageReference Include="WatchFile.Core" />
paket add WatchFile.Core --version 2.3.1
#r "nuget: WatchFile.Core, 2.3.1"
#:package WatchFile.Core@2.3.1
#addin nuget:?package=WatchFile.Core&version=2.3.1
#tool nuget:?package=WatchFile.Core&version=2.3.1
WatchFile API 文档
命名空间
WatchFile.Core
- 主要类和接口WatchFile.Core.Configuration
- 配置管理WatchFile.Core.Configuration.Models
- 配置模型WatchFile.Core.Events
- 事件参数和数据变化分析WatchFile.Core.Monitoring
- 文件监控和临时文件管理WatchFile.Core.Parsing
- 文件解析
核心类
WatchFileManager
文件监控管理器,库的主入口点。提供完整的文件监控、内容变化分析和事件通知功能。
public class WatchFileManager : IDisposable
构造函数
public WatchFileManager(string? configPath = null)
configPath
: 配置文件路径,默认为 "watchfile-config.json"
属性
public bool IsRunning { get; }
获取监控是否正在运行。
public int ActiveWatchersCount { get; }
获取活动监控器数量。
public Dictionary<string, MonitorStatus> WatcherStatuses { get; }
获取所有监控项的状态。
事件
public event EventHandler<FileChangedEventArgs>? FileChanged;
文件变化事件,包含详细的内容差异分析。
文件变化事件。
```csharp
public event EventHandler<MonitorStatusChangedEventArgs>? StatusChanged;
监控状态变化事件。
方法
public async Task StartAsync()
启动文件监控。
public async Task StopAsync()
停止文件监控。
public async Task ReloadConfigurationAsync()
重新加载配置文件。
public void AddHandler(IFileChangedHandler handler)
添加文件变化处理器。
public void RemoveHandler(IFileChangedHandler handler)
移除文件变化处理器。
public WatchItem? GetWatchItem(string id)
获取指定ID的监控项配置。
public IReadOnlyList<WatchItem> GetAllWatchItems()
获取所有监控项配置。
public async Task EnableWatchItemAsync(string id)
启用指定的监控项。
public async Task DisableWatchItemAsync(string id)
禁用指定的监控项。
public async Task<FileParseResult> ParseFileManuallyAsync(string filePath, string watchItemId)
手动解析文件内容。
public void SaveConfiguration(string? path = null)
保存当前配置到文件。
public void CreateDefaultConfiguration(string? path = null)
创建默认配置文件。
public bool ValidateConfiguration(string? path = null)
验证配置文件有效性。
ConfigurationManager
配置文件管理器。
public class ConfigurationManager
构造函数
public ConfigurationManager(string? configPath = null)
方法
public WatchFileConfiguration LoadConfiguration(string? path = null)
加载配置文件。
public void SaveConfiguration(WatchFileConfiguration config, string? path = null)
保存配置文件。
public bool ValidateConfiguration(WatchFileConfiguration config)
验证配置有效性。
public static WatchFileConfiguration CreateDefaultConfiguration()
创建默认配置。
public static bool ValidateConfigurationFile(string configPath)
静态方法:校验配置文件合法性,返回布尔值。
public static bool ValidateConfigurationObject(WatchFileConfiguration config)
静态方法:校验配置对象合法性,返回布尔值。
public static (bool IsValid, string ErrorMessage) ValidateConfigurationFileWithDetails(string configPath)
静态方法:校验配置文件并返回详细错误信息。
public static (bool IsValid, string ErrorMessage) ValidateConfigurationObjectWithDetails(WatchFileConfiguration config)
静态方法:校验配置对象并返回详细错误信息。
public static (bool IsValid, WatchFileConfiguration? Config, string ErrorMessage) LoadAndValidateConfiguration(string configPath)
静态方法:加载并校验配置文件,返回配置对象(推荐使用)。一次调用完成配置文件校验和配置对象获取。
FileParser
静态文件解析器。
public static class FileParser
方法
public static FileParseResult ParseFile(string filePath, FileSettings settings)
解析文件内容。
public static FileParseResult ParseCsv(string filePath, FileSettings settings)
解析CSV文件。
public static FileParseResult ParseExcel(string filePath, FileSettings settings)
解析Excel文件。
事件和数据模型
FileChangedEventArgs
文件变化事件参数,包含详细的内容变化分析。
public class FileChangedEventArgs : EventArgs
{
public string WatchItemId { get; set; } // 监控项ID
public string WatchItemName { get; set; } // 监控项名称
public string FilePath { get; set; } // 文件路径
public WatcherChangeTypes ChangeType { get; set; } // 变化类型
public DateTime Timestamp { get; set; } // 事件时间
public long FileSize { get; set; } // 文件大小
public bool IsSuccess { get; } // 是否处理成功
public Exception? Exception { get; set; } // 异常信息
// 数据内容
public List<Dictionary<string, object>>? ExtractedData { get; set; } // 当前数据
public List<Dictionary<string, object>>? PreviousData { get; set; } // 之前数据
// 变化分析
public DataChangeDetails? ChangeDetails { get; set; } // 详细变化信息
public int DataRowCount { get; } // 当前数据行数
}
DataChangeDetails
数据变化详情分析。
public class DataChangeDetails
{
public List<Dictionary<string, object>> AddedRows { get; set; } // 新增的行
public List<Dictionary<string, object>> DeletedRows { get; set; } // 删除的行
public List<RowChange> ModifiedRows { get; set; } // 修改的行
public int RowCountChange { get; } // 总行数变化
public bool HasChanges { get; } // 是否有变化
public string GetSummary() // 获取变化摘要
}
RowChange
行变化详情。
public class RowChange
{
public int RowIndex { get; set; } // 行索引
public Dictionary<string, object> OldValues { get; set; } // 修改前的值
public Dictionary<string, object> NewValues { get; set; } // 修改后的值
public List<FieldChange> FieldChanges { get; set; } // 字段变化列表
}
FieldChange
字段变化详情。
public class FieldChange
{
public string FieldName { get; set; } // 字段名
public object? OldValue { get; set; } // 旧值
public object? NewValue { get; set; } // 新值
public FieldChangeType ChangeType { get; set; } // 变化类型
}
FieldChangeType
字段变化类型枚举。
public enum FieldChangeType
{
Modified, // 值修改
Added, // 新增字段
Removed // 删除字段
}
public WatcherChangeTypes ChangeType { get; set; } // 变化类型
public DateTime Timestamp { get; set; } // 事件时间
public List<Dictionary<string, object>>? ExtractedData { get; set; } // 提取的数据
public Exception? Exception { get; set; } // 异常信息
public long FileSize { get; set; } // 文件大小
public bool IsSuccess { get; } // 是否成功
public int DataRowCount { get; } // 数据行数
}
### MonitorStatusChangedEventArgs
监控状态变化事件参数。
```csharp
public class MonitorStatusChangedEventArgs : EventArgs
{
public string WatchItemId { get; set; } // 监控项ID
public MonitorStatus Status { get; set; } // 监控状态
public DateTime Timestamp { get; set; } // 状态变化时间
public string Reason { get; set; } // 变化原因
public Exception? Exception { get; set; } // 相关异常
}
FileParseResult
文件解析结果。
public class FileParseResult
{
public bool IsSuccess { get; set; } // 是否成功
public List<Dictionary<string, object>> Data { get; set; } // 解析数据
public Exception? Exception { get; set; } // 异常信息
public int RowCount { get; } // 行数
public string ErrorMessage { get; } // 错误消息
}
接口
IFileChangedHandler
文件变化处理器接口。
public interface IFileChangedHandler
{
Task HandleFileChanged(FileChangedEventArgs args);
}
FileChangedHandlerBase
文件变化处理器基类。
public abstract class FileChangedHandlerBase : IFileChangedHandler
{
public abstract Task HandleFileChanged(FileChangedEventArgs args);
protected virtual bool ShouldHandle(FileChangedEventArgs args);
protected virtual void LogError(string message, Exception? exception = null);
protected virtual void LogInfo(string message);
}
配置模型
WatchFileConfiguration
根配置模型。
public class WatchFileConfiguration
{
public string Version { get; set; } // 配置版本
public GlobalSettings GlobalSettings { get; set; } // 全局设置
public List<WatchItem> WatchItems { get; set; } // 监控项列表
}
WatchItem
监控项配置。
public class WatchItem
{
public string Id { get; set; } // 监控项ID
public string Name { get; set; } // 监控项名称
public bool Enabled { get; set; } // 是否启用
public string Path { get; set; } // 监控路径
public WatchType Type { get; set; } // 监控类型
public bool Recursive { get; set; } // 是否递归
public List<string> FileFilters { get; set; } // 文件过滤器
public List<string> ExcludePatterns { get; set; } // 排除模式
public List<WatchEvent> WatchEvents { get; set; } // 监控事件
public FileSettings FileSettings { get; set; } // 文件设置
public WatchFileSettings WatchFileSettings { get; set; } // 临时文件设置
}
WatchFileSettings
临时文件管理配置。
public class WatchFileSettings
{
public string WatchFileDirectory { get; set; } // 临时文件目录名
public string WatchFileExtension { get; set; } // 临时文件扩展名
public int MaxConcurrentFiles { get; set; } // 最大并发文件数
public bool ThrowOnMissingWatchFile { get; set; } // 临时文件丢失时是否抛异常
public bool EnableDifferenceLogging { get; set; } // 是否启用差异日志
public string DifferenceLogPath { get; set; } // 差异日志路径
}
FileSettings
文件解析设置。
public class FileSettings
{
public FileType FileType { get; set; } // 文件类型
public bool HasHeader { get; set; } // 是否有标题行
public string Delimiter { get; set; } // 分隔符
public string Encoding { get; set; } // 编码
public List<ColumnMapping> ColumnMappings { get; set; } // 列映射
}
public string Version { get; set; } // 配置版本
public GlobalSettings GlobalSettings { get; set; } // 全局设置
public List<WatchItem> WatchItems { get; set; } // 监控项列表
}
### GlobalSettings
全局设置。
```csharp
public class GlobalSettings
{
public bool EnableLogging { get; set; } // 是否启用日志
public string LogLevel { get; set; } // 日志级别
public int BufferTimeMs { get; set; } // 缓冲时间
public int MaxRetries { get; set; } // 最大重试次数
public string LogFilePath { get; set; } // 日志文件路径
}
WatchItem
监控项配置。
public class WatchItem
{
public string Id { get; set; } // 唯一标识
public string Name { get; set; } // 显示名称
public bool Enabled { get; set; } // 是否启用
public string Path { get; set; } // 监控路径
public WatchType Type { get; set; } // 监控类型
public bool Recursive { get; set; } // 是否递归
public List<string> FileFilters { get; set; } // 文件过滤器
public List<WatchEvent> WatchEvents { get; set; } // 监控事件
public FileSettings FileSettings { get; set; } // 文件设置
}
FileSettings
文件设置。
public class FileSettings
{
public FileType FileType { get; set; } // 文件类型
public bool HasHeader { get; set; } // 是否有标题行
public string Delimiter { get; set; } // 分隔符
public string Encoding { get; set; } // 编码
public string SheetName { get; set; } // 工作表名称
public int StartRow { get; set; } // 开始行号
public List<ColumnMapping> ColumnMappings { get; set; } // 列映射
}
ColumnMapping
列映射配置。
public class ColumnMapping
{
public object SourceColumn { get; set; } // 源列(名称或索引)
public string TargetName { get; set; } // 目标属性名
public DataType DataType { get; set; } // 数据类型
public bool Required { get; set; } // 是否必需
public string Format { get; set; } // 格式字符串
}
枚举
WatchType
监控类型。
public enum WatchType
{
Directory, // 目录
File // 文件
}
WatchEvent
监控事件。
public enum WatchEvent
{
Created, // 创建
Modified, // 修改
Deleted, // 删除
Renamed // 重命名
}
FileType
文件类型。
public enum FileType
{
CSV, // CSV文件
Excel // Excel文件
}
DataType
数据类型。
public enum DataType
{
String, // 字符串
Integer, // 整数
Decimal, // 小数
DateTime, // 日期时间
Boolean // 布尔值
}
MonitorStatus
监控状态。
public enum MonitorStatus
{
Stopped, // 停止
Starting, // 启动中
Running, // 运行中
Error, // 错误
Paused // 暂停
}
LogLevel
日志级别。
public enum LogLevel
{
Debug, // 调试
Info, // 信息
Warning, // 警告
Error // 错误
}
使用示例
基本监控
var manager = new WatchFileManager("config.json");
manager.FileChanged += (sender, e) =>
{
Console.WriteLine($"文件 {e.FilePath} 发生 {e.ChangeType} 变化");
if (e.ExtractedData != null)
{
Console.WriteLine($"提取了 {e.DataRowCount} 行数据");
}
};
await manager.StartAsync();
// ... 应用运行
await manager.StopAsync();
自定义处理器
public class MyHandler : FileChangedHandlerBase
{
public override async Task HandleFileChanged(FileChangedEventArgs args)
{
if (!ShouldHandle(args)) return;
try
{
// 处理逻辑
LogInfo($"处理文件: {args.FilePath}");
}
catch (Exception ex)
{
LogError("处理失败", ex);
}
}
}
manager.AddHandler(new MyHandler());
配置文件校验和加载(v2.1+)
// 推荐:一次调用完成校验和加载
var (isValid, config, errorMessage) = ConfigurationManager.LoadAndValidateConfiguration("config.json");
if (isValid && config != null)
{
Console.WriteLine("✅ 配置文件有效");
// 直接使用配置对象,无需创建监控实例
Console.WriteLine($"监控项总数: {config.WatchItems.Count}");
Console.WriteLine($"启用的监控项: {config.WatchItems.Count(w => w.Enabled)}");
Console.WriteLine($"全局设置 - 日志级别: {config.GlobalSettings.LogLevel}");
// 分析监控项
foreach (var item in config.WatchItems.Where(w => w.Enabled))
{
Console.WriteLine($"- {item.Name}: {item.Path} ({item.FileSettings.FileType})");
}
}
else
{
Console.WriteLine($"❌ 配置文件无效: {errorMessage}");
}
// 其他静态校验方法
bool isValidSimple = ConfigurationManager.ValidateConfigurationFile("config.json");
var (valid, error) = ConfigurationManager.ValidateConfigurationFileWithDetails("config.json");
动态管理监控项
// 启用监控项
await manager.EnableWatchItemAsync("item-id");
// 禁用监控项
await manager.DisableWatchItemAsync("item-id");
// 获取状态
var statuses = manager.WatcherStatuses;
foreach (var status in statuses)
{
Console.WriteLine($"{status.Key}: {status.Value}");
}
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
.NET Framework | net461 is compatible. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
-
.NETFramework 4.6.1
- CsvHelper (>= 30.0.1)
- Newtonsoft.Json (>= 13.0.3)
- NPOI (>= 2.6.2)
- System.Text.Encoding.CodePages (>= 6.0.0)
- System.ValueTuple (>= 4.5.0)
-
net6.0
- CsvHelper (>= 30.0.1)
- Newtonsoft.Json (>= 13.0.3)
- NPOI (>= 2.6.2)
- System.Text.Encoding.CodePages (>= 6.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
v2.3.1:
- 🆕 新增 CurrentData 属性:语义更明确地表示变化后的完整文件状态
- 🔄 改进数据展示逻辑:优先使用 CurrentData 显示变化后的完整内容
- 🛡️ 保持向后兼容:ExtractedData 属性继续有效,不影响现有代码
- 📊 用户体验优化:更清晰地区分变化分析和完整文件内容展示
- 🧪 测试程序更新:控制台测试程序同步支持新的数据显示方式
v2.3.0:
- 🚀 新增配置驱动的自动删除功能:DeleteAfterProcessing
- 🛡️ 智能文件清理:自动删除主文件和缓存文件
- 🔧 强制删除机制:自动清除只读、隐藏、系统属性
- 📁 缓存目录管理:自动清理空的缓存目录
- ❌ 重要变更:移除2.2.0版本的手动删除API(SafeDeleteFileAsync等)
- 🔄 架构优化:改为配置驱动的自动删除,更适合工控环境
- 🧹 代码重构:清理未使用的方法,简化API设计
- ⚙️ 使用方式:现在只需在配置中设置"DeleteAfterProcessing": true
v2.2.0:
- 🚀 新增安全删除功能:SafeDeleteFileAsync, SafeDeleteMonitoredFileAsync
- 🛡️ 强制删除机制:自动清除只读、隐藏、系统属性,解决工控环境权限问题
- 🔧 智能文件处理:临时禁用监控事件,避免删除操作触发自身监控
- 📦 自动编码处理:内置 System.Text.Encoding.CodePages,无需手动注册
- 🧪 完整测试支持:ConsoleTest 集成安全删除测试和配置控制
- ⚡ 性能优化:简化文件释放检查,移除复杂的独占访问检测
v2.1.1:
- 重要修复:GetAllWatchItems现在返回所有配置项,包括路径不存在的项
- 改进:将路径验证从配置加载阶段移至监控启动阶段
- 增强:用户现在可以看到完整的配置列表,便于识别有问题的监控项
- 优化:在启动监控时提供更友好的路径错误提示
v2.1.0:
- 新增静态配置校验方法:ValidateConfigurationFile, ValidateConfigurationObject
- 新增LoadAndValidateConfiguration方法:一次调用完成配置校验和加载
- 修复GetAllWatchItems在StartAsync之前调用返回空列表的问题
- 改进配置管理器,支持在构造函数中加载配置
- 增强API文档和使用示例
v2.0.0:
- 支持详细的文件内容变化分析
- 优化工控环境大量小文件监控
- 临时文件缓存机制
- 支持 .NET Framework 4.6.1+ 和 .NET 6+
- CSV/Excel 文件智能差异检测
- 可配置的列映射和数据类型转换