How to convert byte array to InMemoryRandomAccessStream or IRandomAccessStream in windows 8

Alen Lee picture Alen Lee · May 6, 2013 · Viewed 18.1k times · Source

now I've had a problem that is how to convert byte array to InMemoryRandomAccessStream or IRandomAccessStream in windows 8?

This is my code, but It did't work, refer the following code

internal static async Task<InMemoryRandomAccessStream> ConvertTo(byte[] arr)
{
    InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
    Stream stream = randomAccessStream.AsStream();
    await stream.WriteAsync(arr, 0, arr.Length);
    await stream.FlushAsync();

    return randomAccessStream;
}

And then I create the RandomAccessStreamReference and set the requst datapack in order to share the image to other app

    private static async void OnDeferredImageStreamRequestedHandler(DataProviderRequest Request)
    {
        DataProviderDeferral deferral = Request.GetDeferral();
        InMemoryRandomAccessStream stream = await ConvertTo(arr);
        RandomAccessStreamReference referenceStream =
                    RandomAccessStreamReference.CreateFromStream(stream);
        Request.SetData(referenceStream);
    }

But the result is I can't share the image byte array to other app, Does my code have a problem? In my opinion, the error occurs when convert byte[] to InMemoryRandomAccessStream, but it did't throw exception.

Anybody know how to do it? And also if you can convert the byte array to IRandomAccessStream, the same can help me. Or another error in my code?

Answer

Immo Landwerth picture Immo Landwerth · Jun 28, 2013

On Windows 8.1 it's even easier as we added the AsRandomAccessStream extension method:

internal static IRandomAccessStream ConvertTo(byte[] arr)
{
    MemoryStream stream = new MemoryStream(arr);
    return stream.AsRandomAccessStream();
}