Winrt StreamWriter & StorageFile does not completely Overwrite File

不想你离开。 提交于 2019-12-10 19:35:10

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/16425396/winrt-streamwriter-storagefile-does-not-completely-overwrite-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!