user3646098
user3646098

Reputation: 299

How to write a stream to a file in Windows Runtime?

There are lots of questions around, but mostly are about writing strings to a file. I'm a bit confused!

What is the proper way to write a stream to a file?

what I did:

Stream stream = await GetStream(source);

var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("TempUsersFile", CreationCollisionOption.ReplaceExisting);
var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);

using (var dataWriter = new Windows.Storage.Streams.DataWriter(fileStream))
{
    // How can I write to buffer and write to the file
}

Upvotes: 0

Views: 2108

Answers (2)

Romasz
Romasz

Reputation: 29792

There are many ways of writing a stream to file and they also depend on your needs. The method below performs asynchronous operation with a specified buffer:

public async Task SaveStreamToFile(Stream streamToSave, string fileName, CancellationToken cancelToken)
{
    StorageFile file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
    using (Stream fileStram = await file.OpenStreamForWriteAsync())
    {
        const int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];

        int bytesread = 0;
        while ((bytesread = await streamToSave.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
        {
            await fileStram.WriteAsync(buf, 0, bytesread);
            cancelToken.ThrowIfCancellationRequested();
        }
    }
}

I've implemented also a CancellationToken in case there will be a need to cancel the long running Task.

Upvotes: 1

LVBen
LVBen

Reputation: 2061

I would recommend using the StreamReader and StreamWriter classes:

 StreamWriter sw = new StreamWriter(outstream);
 StreamReader sr = new StreamReader(instream);

 while (!sr.EndOfStream)
 {
    int ch = sr.Read();
    sw.Write(ch);
 }

Upvotes: 1

Related Questions