|
1. 文件存在性检查与创建
- /// <summary>
- /// 安全文件创建器(自动处理目录缺失)
- /// </summary>
- public static void SafeFileCreate(string path)
- {
- if (!File.Exists(path))
- {
- var directory = Path.GetDirectoryName(path);
- // 自动创建缺失目录[3,5](@ref)
- if (!Directory.Exists(directory))
- {
- Directory.CreateDirectory(directory);
- }
- File.Create(path).Dispose(); // 立即释放文件句柄
- }
- }
复制代码 2. 原子化文件写入
- /// <summary>
- /// 安全写入文本文件(防写入中断)
- /// </summary>
- public static void AtomicWrite(string path, string content)
- {
- string tempFile = Path.GetTempFileName();
- try
- {
- // 先写入临时文件[2](@ref)
- File.WriteAllText(tempFile, content, Encoding.UTF8);
- // 原子替换目标文件[5](@ref)
- File.Replace(tempFile, path, null);
- }
- finally
- {
- if (File.Exists(tempFile))
- File.Delete(tempFile);
- }
- }
复制代码 3. 实时文件监控
- /// <summary>
- /// 智能文件变更监听服务
- /// </summary>
- public class FileWatcher
- {
- private FileSystemWatcher _watcher;
- public void Start(string path, string filter = "*.*")
- {
- _watcher = new FileSystemWatcher
- {
- Path = path,
- Filter = filter,
- NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName,
- EnableRaisingEvents = true
- };
- // 防事件重复触发[3](@ref)
- _watcher.Changed += (s, e) => OnChangedDelayed(e);
- _watcher.Created += (s, e) => OnCreatedDelayed(e);
- }
- private async void OnChangedDelayed(FileSystemEventArgs e)
- {
- await Task.Delay(500); // 等待文件释放
- Console.WriteLine($"文件变更:{e.Name}");
- }
- }
复制代码
|
|