如何确保 c# 在程序停止时完成写入文件?
How to ensure c# finishes writing a file when program is stopped?
我有一个 c# 控制台应用程序,它经常快速地将大约 1-2mb 的数据写入一个文件(不断覆盖同一个文件)。然后我 运行 程序像这样无限循环
@echo off
:while
(
C:\sync.exe
goto :while
)
然后 c# 会这样写文本
private static async Task WriteFile(string filePath, string text)
{
string base_path = AppDomain.CurrentDomain.BaseDirectory;
string file_path = Path.Combine(base_path, filePath);
using (StreamWriter outputFile = new StreamWriter(file_path))
{
await outputFile.WriteAsync(text);
}
}
但我注意到,当我使用 ctrl+c 结束程序或停止调试器时,当它正在写入时,它会停止写入并使文件损坏并丢失数据.
有没有一种方法可以确保如果程序在写入过程中停止,它要么撤消更改(它会覆盖之前存在的文件),让旧的文件再次返回,要么以某种方式完成写入(这将花费不到一秒钟的时间)?
Is there a way that I can ensure that if the program is stopped mid-write, it either undoes the change (it overwrites the previous file that was there) leaving the old one back again, or it somehow finishes writing (which will take less than a second)?
是...写入不同的文件。写入完成后,使用Copy
方法的this prototype复制文件,将第三个参数设置为true
。
private static async Task WriteFile(string filePath, string text)
{
string temp_file = File.GetTempFileName();
string base_path = AppDomain.CurrentDomain.BaseDirectory;
using (StreamWriter outputFile = new StreamWriter(temp_file))
{
await outputFile.WriteAsync(text);
}
string file_path = Path.Combine(base_path, filePath);
File.Copy(temp_file, file_path, true);
File.Delete(temp_file);
}
我有一个 c# 控制台应用程序,它经常快速地将大约 1-2mb 的数据写入一个文件(不断覆盖同一个文件)。然后我 运行 程序像这样无限循环
@echo off
:while
(
C:\sync.exe
goto :while
)
然后 c# 会这样写文本
private static async Task WriteFile(string filePath, string text)
{
string base_path = AppDomain.CurrentDomain.BaseDirectory;
string file_path = Path.Combine(base_path, filePath);
using (StreamWriter outputFile = new StreamWriter(file_path))
{
await outputFile.WriteAsync(text);
}
}
但我注意到,当我使用 ctrl+c 结束程序或停止调试器时,当它正在写入时,它会停止写入并使文件损坏并丢失数据.
有没有一种方法可以确保如果程序在写入过程中停止,它要么撤消更改(它会覆盖之前存在的文件),让旧的文件再次返回,要么以某种方式完成写入(这将花费不到一秒钟的时间)?
Is there a way that I can ensure that if the program is stopped mid-write, it either undoes the change (it overwrites the previous file that was there) leaving the old one back again, or it somehow finishes writing (which will take less than a second)?
是...写入不同的文件。写入完成后,使用Copy
方法的this prototype复制文件,将第三个参数设置为true
。
private static async Task WriteFile(string filePath, string text)
{
string temp_file = File.GetTempFileName();
string base_path = AppDomain.CurrentDomain.BaseDirectory;
using (StreamWriter outputFile = new StreamWriter(temp_file))
{
await outputFile.WriteAsync(text);
}
string file_path = Path.Combine(base_path, filePath);
File.Copy(temp_file, file_path, true);
File.Delete(temp_file);
}