Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Windows.Storage.Streams.IRandomAccessStream to System.IO.Stream

How can I convert Windows.Storage.Streams.IRandomAccessStream to System.IO.Stream?

I'm using a C# library which accepts System.IO.Stream as input, but when I open files in Metro I get Windows.Storage.Streams.IRandomAccessStream.

like image 224
MBZ Avatar asked Nov 29 '12 21:11

MBZ


2 Answers

The easiest way is to call AsStream.

like image 197
Stephen Cleary Avatar answered Nov 20 '22 20:11

Stephen Cleary


You can convert Windows.Storage.Streams.IRandomAccessStream to a byte[] and then convert byte[] to a System.IO.Stream.

Byte[] from IRandomAccessStream

        var file = await new FileOpenPicker().PickSingleFileAsync();
        var fStream = await file.OpenAsync(FileAccessMode.Read);

        var reader = new DataReader(fStream.GetInputStreamAt(0));
        var bytes = new byte[fStream.Size];
        await reader.LoadAsync((uint)fStream.Size);
        reader.ReadBytes(bytes);

Stream from Byte[]

var stream = new MemoryStream(bytes);
like image 37
Mayank Avatar answered Nov 20 '22 19:11

Mayank