C# 如何在读取文件之前等待流完成对文件的写入
我的代码很简单;它使用StringBuilder和FileStream将数据写入文本文件,然后[可选]打开文本文件进行查看:C# 如何在读取文件之前等待流完成对文件的写入,c#,C#,我的代码很简单;它使用StringBuilder和FileStream将数据写入文本文件,然后[可选]打开文本文件进行查看: public async Task ExportData(data) { var sb = new StringBuilder(); sb.AppendLine(BuildStringFromData()); var dir = $@"C:\Ortund\xExports\{DateTime.Now.Date.ToString (
public async Task ExportData(data)
{
var sb = new StringBuilder();
sb.AppendLine(BuildStringFromData());
var dir = $@"C:\Ortund\xExports\{DateTime.Now.Date.ToString
("yyyy-MM-dd", CultureInfo.InvariantCulture)}";
var fullPath = $@"{dir}\{filename}.txt";
var stream = new FileStream(fullPath, FileMode.CreateNew, FileAccess.ReadWrite);
var bytes = Encoding.UTF8.GetBytes(sb.ToString());
await stream.WriteAsync(bytes, 0, bytes.Length);
if (MessageBox.Show("Open the file?", "Open?", MessageBoxButton.YesNo)
== MessageBoxResult.Yes)
{
System.Diagnostics.Process.Start(fullPath);
}
}
我等待着文件流中的写入操作,认为这会暂停这个特定方法的执行,直到所有字节都被写入,但事实并非如此
发生的情况是,打开文件的提示立即出现,当我打开它时,它是空白的。记事本++只在几秒钟后通知我文件已被更改,并询问我是否要重新加载它,然后我看到导出的数据
在请求用户打开文件之前,如何让执行等待文件数据完全写入?我忽略了这一点 根据@Evk对该问题的评论,我使用块将FileStream放入一个
,但我也将其移动到一个新方法中,该方法将数据和文件路径作为参数:
private async Task WriteDataToFile(List<ViewModel> data, string path)
{
using (var fs = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite))
{
var sb = new StringBuilder();
// Loop through the data and build the string.
var bytes = Encoding.UTF8.GetBytes(sb.ToString());
await fs.WriteAsync(bytes, 0, bytes.Length);
}
}
private async Task WriteDataToFile(列表数据、字符串路径)
{
使用(var fs=new FileStream(路径,FileMode.CreateNew,FileAccess.ReadWrite))
{
var sb=新的StringBuilder();
//循环遍历数据并构建字符串。
var bytes=Encoding.UTF8.GetBytes(sb.ToString());
等待fs.WriteAsync(字节,0,字节.长度);
}
}
使用关闭了我忽略的文件流。调用Write()
方法,而不是WriteAsync()
@MichałTurczyn,我先尝试了;行为没有什么不同。然后,您需要关闭流…在打开文件之前关闭流以刷新所有缓冲区(最好使用(var stream=new FileStream(…)
将整个内容包装到中。如果出于任何原因您不想关闭-调用wait stream.FlushAsync()
,则fs.close()也会有所帮助最后,以完成流操作。