public static class FileSafeWrite{public static void WriteAllTextAtomically(string filePath, string content){// 定义临时文件路径string tempFilePath = filePath + ".tmp";try{// 将内容写入临时文件using (var streamWriter = new StreamWriter(tempFilePath, append: false)){streamWriter.Write(content);streamWriter.Flush(); // 将缓冲区数据刷到操作系统}// 替换原始文件if (File.Exists(filePath)){File.Replace(tempFilePath, filePath, null);}else{File.Move(tempFilePath, filePath);}}catch{//尝试清理临时文件if (File.Exists(tempFilePath)){try { File.Delete(tempFilePath); } catch { /* 忽略清理错误 */ }}throw; // 重新抛出原始异常}}}
c# 保存文件 - 先保存到临时文件,保存成功后修改文件名
留待后查,同时方便他人
联系我:renhanlinbsl@163.com
联系我:renhanlinbsl@163.com