如何在读取之前等待流完成写入文件

时间:2017-11-22 10:39:22

标签: c#

我的代码非常简单;它使用StringBuilder和FileStream将数据写入文本文件,然后[可选]打开文本文件以供查看:

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);
    }
}

我等待文件流中的写入操作,认为这将暂停执行此特定方法,直到所有字节都已写入,但这不是正在发生的事情。

正在发生的事情是打开文件的提示会立即出现,当我打开它时,它的空白。 Notepad ++仅在几秒钟后通知我对文件进行了更改并询问我是否要重新加载它,然后我看到导出的数据。

如果在要求用户打开文件之前完全写入文件数据,我怎样才能执行等待?

1 个答案:

答案 0 :(得分:0)

我忽视了这一点上的显而易见......

根据@Evk对问题的评论,我将FileStream放入using块,但我也将其移动到一个新方法,该方法将数据和文件路径作为参数:

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);
    }
}

使用关闭FileStream,这是我忽略的。