3

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

RallyRabbit
  • 433
  • 1
  • 8
  • 20

2 Answers2

5

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);
}
Denis
  • 4,115
  • 1
  • 18
  • 20
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.

Damir Arh
  • 17,637
  • 2
  • 45
  • 83
  • FileIO didn't work well, seems that it wants you to put together all your data first and then output it rather than doing it incrementally. – RallyRabbit May 08 '13 at 12:19