Winrt StreamWriter & StorageFile does not complete

2019-07-04 03:46发布

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.

The code is as such:

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

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

2条回答
老娘就宠你
2楼-- · 2019-07-04 03:52

Alternatively you can set length of the stream to 0 with SetLength method before using StreamWriter:

var stream = await file.OpenStreamForWriteAsync();
stream.SetLength(0);
using (var writer = new StreamWriter(stream))
{
    writer.Write(text);
}
查看更多
姐就是有狂的资本
3楼-- · 2019-07-04 03:53

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

FileIO.WriteTextAsync(selectedFileToSave, newTextContents);

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.

查看更多
登录 后发表回答