26 comments on “How to Convert byte Array to IRandomAccessStream

  1. Thanks for the post! Been tearing my hair out at this one for hours :-)

    I was using this approach but my class stopped working with the latest windows 8 release. The differences was my class didn’t implement the ReadAsync, FlushAsync and WriteAsync methods.

    I’m guessing something changed with SetSource to do with threading.

  2. Pingback: Converting StorageFiles (png) to a Byte[] in order to display as an Image in WinRT (C#) - Derik Whittaker - Devlicio.us - Just the Tasty Bits

  3. I read PDF content as byte[] and then I use above method. It does work.
    But for the image (png, bmp, jpeg) byet[], it works properly.
    Why it doesn’t work for PDF byte[]. Do you have any good ideas?

    • In above comment, there was some mistakes. Sorry!!!
      I read PDF content as byte[] and then I use above method. It doesn’t work.
      But for the image (png, bmp, jpeg) byet[], it works properly
      Why it doesn’t work for PDF byte[]. Do you have any good ideas?

    • hey yu lin, would you paste some code sample showing what your are trying to achieve with the PDF bytes converted into randomaccessstream… maybe the control your are trying to load requires something extra…

      • FileOpenPicker filepickerOpen = new FileOpenPicker();
        filepickerOpen.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        filepickerOpen.ViewMode = PickerViewMode.Thumbnail;
        filepickerOpen.FileTypeFilter.Clear();
        filepickerOpen.FileTypeFilter.Add(“.png”);
        filepickerOpen.FileTypeFilter.Add(“.pdf”);
        StorageFile storage= await filepickerOpen.PickSingleFileAsync();

        byte[] buffer = WindowsRuntimeBufferExtensions.ToArray(await FileIO.ReadBufferAsync(storage));
        using (MemoryStream ms = new MemoryStream(buffer))
        {
        var ims = new InMemoryRandomAccessStream();
        DataWriter dataWriter = new DataWriter(ims);
        dataWriter.WriteBytes(buffer);
        dataWriter.StoreAsync();
        ims.Seek(0);
        BitmapImage img = new BitmapImage();
        img.SetSource(ims);
        ImageDocument.Source = img;
        }

      • oh I see what is going on… you cannot load pdf bytes to bitmapimage (ImageSource)… it only supports different image types (e.g. png, gif, tiff, bmp)… for pdf there is no native control that can display the data… you might want to look for a 3rd part control, or just launch the pdf file using the launcher class… it will automatically use the Reader app to open the file.

  4. no. I don’t want to launch with Reader cos it is look alike changing to another application. I only want to show within my application. I have already looked for 3rd part control. I found one. It is
    “Foxit Embedded PDF SDK”(http://www.foxitsoftware.com/products/sdk/embedded/windows/) . We can get source code from this side. But problem is trial version only for 30days. I haven’t found another vendor that are full free. I have also looked for silverlight library. But nothing works …:(
    Do you have any other options?

  5. Dude, you saved my life. I searched everywhere online(yeah, was a bit desperate). Finally landed here, I just implemented it and found that one to be working. Thanks a lot

  6. Thanks a lot, I was looking all over the place for a solution, and this worked out flawlessly for me. I’m surprised I haven’t found really anyone else with this problem.

    • @Nkosi Dean: glad the solution worked for you… I guess the main issue is to pass this transitional period between the System.IO and the new memory streams that are introduced in windows.storage namespace. Probably there will be more and more options for the new streams.

  7. Dude i have an error at

    public Windows.Foundation.IAsyncOperation FlushAsync()
    {
    var outputStream = this.GetOutputStreamAt(0);
    return outputStream.FlushAsync();
    }

    and the error says
    “Error6 Using the generic type ‘Windows.Foundation.IAsyncOperation’ requires 1 type arguments”? lol i am new to this but have no idea what that means any help will be appreciated :P awesome post btw!
    :D

    • hey there,

      I am not sure how or why but the method signature was not correct, nice catch mate… the correct signature should be:

      public Windows.Foundation.IAsyncOperation<bool> FlushAsync()

      I just updated the post as well…

      good luck…

  8. Hi, everything seems to be working but i still can’t seem to display the image on the screen
    here’s my code:
    public void BytesToImage(byte[] bytes)
    {
    BitmapImage bitmapImage = new BitmapImage();
    MemoryStream ms = new MemoryStream(bytes);
    var randomAccessStream = new MemoryRandomAccessStream(ms);
    bitmapImage.SetSource(randomAccessStream);
    ImgResult.Source = bitmapImage;
    ImgResult.Visibility = Visibility.Visible;
    }
    my application is running and everything but i cant get it to display the image.

    • hey sorry for the late response, but did you try to use bitmapImage.SetSourceAsync(randomAccessStream)? I think the problem is with the UI synchronization context interfering with the async operations in the memoryrandomaccessstream.

  9. I used this on WP8 but found I needed to change this.GetInputStream(0) to this.GetInputStream(Position) and this.GetOutputStream(0) to this.GetOutputStream(Position). This way, subsequent calls to ReadAsync, etc will use the current stream position.

  10. I used this class to convert an in-memory stream of samples to something that Sharpdx.XAudio2 could play. The first second or so was repeating constantly. I fixed this by changing the SeekOrigin in MemoryRandomAccessStream.GetInputStreamAt and .GetOutputStreamAt from SeekOrigin.Begin to SeekOrigin.Current.

    Maybe this is a problem with XAudio2? Hopefully it will help someone else out anyway.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s