| | |
| | | /// <param name="dataPath">数据目录路径</param> |
| | | public FilePersistenceService(string dataPath = "Data") |
| | | { |
| | | _dataPath = dataPath; |
| | | // 转换为绝对路径(基于当前工作目录) |
| | | _dataPath = Path.GetFullPath(dataPath); |
| | | |
| | | try |
| | | { |
| | |
| | | } |
| | | |
| | | /// <summary> |
| | | /// 原子性写入文件(使用临时文件+替换模式) |
| | | /// 写入文件(直接写入,简化版本) |
| | | /// </summary> |
| | | private async Task WriteFileAtomicAsync(string filePath, string content) |
| | | { |
| | | var tempPath = filePath + ".tmp"; |
| | | |
| | | try |
| | | // 确保目标文件的父目录存在 |
| | | var directory = Path.GetDirectoryName(filePath); |
| | | if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) |
| | | { |
| | | // 写入临时文件 |
| | | await File.WriteAllTextAsync(tempPath, content, Encoding.UTF8); |
| | | Directory.CreateDirectory(directory); |
| | | } |
| | | |
| | | // 原子性替换目标文件 |
| | | File.Replace(tempPath, filePath, null); |
| | | } |
| | | catch |
| | | { |
| | | // 清理临时文件 |
| | | if (File.Exists(tempPath)) |
| | | { |
| | | try |
| | | { |
| | | File.Delete(tempPath); |
| | | } |
| | | catch |
| | | { |
| | | // 忽略清理失败 |
| | | } |
| | | } |
| | | throw; |
| | | } |
| | | // 直接写入文件 |
| | | await File.WriteAllTextAsync(filePath, content, Encoding.UTF8); |
| | | } |
| | | |
| | | /// <summary> |