Winrt StreamWriter &StorageFile 不会完全覆盖文件 [英] Winrt StreamWriter & StorageFile does not completely Overwrite File

查看:34
本文介绍了Winrt StreamWriter &StorageFile 不会完全覆盖文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的快速搜索一无所获.所以,我已经开始使用一些相当迂回的方式在我的 WinRT 应用程序中使用 StreamWriter.阅读效果很好,写作效果不同.我看到的是,当我选择要写入的文件时,如果我选择一个新文件,那就没问题了.该文件是按照我的预期创建的.如果我选择覆盖一个文件,那么文件被覆盖到一个点,但是流停止写入的点,如果原始文件很大,那么旧内容存在于我的新流写入的位置.

Quick search here yielded nothing. So, I have started using some rather roundabout ways to use StreamWriter in my WinRT Application. Reading works well, writing works differently. What' I'm seeing is that when I select my file to write, if I choose a new file then no problem. The file is created as I expect. If I choose to overwrite a file, then the file is overwritten to a point, but the point where the stream stops writing, if the original file was large, then the old contents exist past where my new stream writes.

代码如下:

public async void WriteFile(StorageFile selectedFileToSave)
{
    // At this point, selectedFileToSave is from the Save File picker so can be a enw or existing file
    StreamWriter writeStream;
    Encoding enc = new UTF8Encoding();
    Stream dotNetStream;

    dotNetStream = await selectedFileToSave.OpenStreamForWriteAsync();
    StreamWriter writeStream = new StreamWriter(dotNetStream, enc);

    // Do writing here

    // Close
    writeStream.Write(Environment.NewLine);
    await writeStream.FlushAsync();
    await dotNetStream.FlushAsync();
}

谁能提供我可能遗漏的线索?WinRT 中缺少很多功能,因此没有真正遵循解决此问题的方法

Can anyone offer clues on what I could be missing? There are lots of functions missing in WinRT, so not really following ways to get around this

推荐答案

为什么不直接使用 FileIO 类?你可以打电话:

Why not just use the helper methods in FileIO class? You could call:

FileIO.WriteTextAsync(selectedFileToSave, newTextContents);

如果你真的需要一个StreamWriter,首先通过调用

If you really need a StreamWriter, first truncate the file by calling

FileIO.WriteBytesAsync(selectedFileToSave, new byte[0]);

然后继续使用您现有的代码.

And then continue with your existing code.

这篇关于Winrt StreamWriter &StorageFile 不会完全覆盖文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆