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

这一生的挚爱 提交于 2020-07-05 00:01:16

问题


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?


回答1:


Add the using statement at the top of the document.

using System.Runtime.InteropServices.WindowsRuntime;
internal static async Task<InMemoryRandomAccessStream> ConvertTo(byte[] arr)
{
    InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
    await randomAccessStream.WriteAsync(arr.AsBuffer());
    randomAccessStream.Seek(0); // Just to be sure.
                    // I don't think you need to flush here, but if it doesn't work, give it a try.
    return randomAccessStream;
}



回答2:


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();
}



回答3:


In one line:

internal static IRandomAccessStream ConvertTo(byte[] arr)
{
    return arr.AsBuffer().AsStream().AsRandomAccessStream();
}


来源:https://stackoverflow.com/questions/16397509/how-to-convert-byte-array-to-inmemoryrandomaccessstream-or-irandomaccessstream-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!