我需要在我的项目中写一个大文件.
我学到的是:
我不应该将大文件直接写入目标路径,因为这可能会留下一个不完整的文件,以防应用程序在写入时崩溃.
相反,我应该写一个临时文件并移动(重命名)它.(称为原子文件操作)
我的代码片段:
[NotNull]
public static async Task WriteAllTextAsync([NotNull] string path, [NotNull] string content)
{
string temporaryFilePath = null;
try {
temporaryFilePath = Path.GetTempFileName();
using (var stream = new StreamWriter(temporaryFilePath, true)) {
await stream.WriteAsync(content).ConfigureAwait(false);
}
File.Delete(path);
File.Move(temporaryFilePath, path);
}
finally {
if (temporaryFilePath != null) File.Delete(temporaryFilePath);
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题:
如果应用程序在File.Delete和之间崩溃,则文件将丢失File.Move.我可以避免这个吗?
编写大文件还有其他最佳实践吗?
我的代码有什么建议吗?