Reputation: 5264
I just upgraded my project from Win 8 to Win 8.1 and I'm trying to take advantage of some of the new features in the SDK. One of those is the new AsRandomAccessStream
extension method. The problem I'm having is when I use it, I'm getting an Unauthorized Access Exception.
Exception:Caught: "MemoryStream's internal buffer cannot be accessed." (System.UnauthorizedAccessException) A System.UnauthorizedAccessException was caught: "MemoryStream's internal buffer cannot be accessed." Time: 3/11/2014 10:23:11 AM Thread:[4308]
BitmapImage image = new BitmapImage();
var imageStream = new MemoryStream(imageBytes as byte[]);
image.SetSource(imageStream.AsRandomAccessStream());
any thoughts?
Upvotes: 8
Views: 2488
Reputation: 367
A simple workaround is to combine some extension methods.
var image = new BitmapImage();
var imageSource = imageBytes.AsBuffer().AsStream().AsRandomAccessStream();
image.SetSource(imageSource);
Upvotes: 1
Reputation:
I encountered this problem today and to me, it appears as an API bug/inconsistency.
In .NET 4, calls to MemoryStream.GetBuffer() require the usage of certain constructors (see https://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx). More specifically, the buffer of the MemoryStream must be marked as exposable.
Now, AsRandomAccessStream() calls MemoryStream.GetBuffer(). However, in Win8.1, the constructor for setting the expose-ability of a MemoryStream is missing. Therefore, when you create the MemoryStream, use the default empty constructor and then call Write().
Thus, I think this should work.
BitmapImage image = new BitmapImage();
var imageStream = new MemoryStream();
imageStream.Write(yourdata, 0, yourdata.Length);
image.SetSource(imageStream.AsRandomAccessStream());
Upvotes: 5