Search code examples
c#.netwindows-8windows-store-apps

How to get a stream from a byte array in a windows8 store app


I have been trying get a stream from a byte array in metro style app using the following code.

InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();
memoryStream.AsStreamForWrite().Write(byteArray, 0, byteArray.Length);
memoryStream.Seek(0);

It executes with no errors but stream size is zero (0). Can anybody tell me why is its size is zero?


Solution

  • You can use the DataWriter and DataReader classes. For example ...

    // put bytes into the stream
    var ms = new InMemoryRandomAccessStream();
    var dw = new Windows.Storage.Streams.DataWriter(ms);
    dw.WriteBytes(new byte[] { 0x00, 0x01, 0x02 });
    await dw.StoreAsync();
    
    // read them out
    ms.Seek(0);
    byte[] ob = new byte[ms.Size];
    var dr = new Windows.Storage.Streams.DataReader(ms);
    await dr.LoadAsync((uint)ms.Size);
    dr.ReadBytes(ob);