Convert Windows.Storage.Streams.IRandomAccessStream to System.IO.Stream
The easiest way is to call AsStream
.
Is there a way to convert a System.IO.Stream to a Windows.Storage.Streams.IRandomAccessStream?
To use the extensions: you must add "using System.IO"
In Windows8, .NET and WinRT types are generally converted to/from compatible types under the hood so you don't have to care about it.
For streams, however, there are helper methods to convert between WinRT and .NET streams:
For converting from WinRT streams -> .NET streams:
InMemoryRandomAccessStream win8Stream = GetData(); // Get a data stream from somewhere.
System.IO.Stream inputStream = win8Stream.AsStream()
For converting from .NET streams -> WinRT streams:
Windows.Storage.Streams.IInputStream inStream = stream.AsInputStream();
Windows.Storage.Streams.IOutputStream outStream = stream.AsOutputStream();
UPDATE: 2013-09-01
Let it not be said that Microsoft doesn't listen to it's developer community ;)
In the announcement for .NET FX 4.5.1, Microsoft states that:
Many of you have been wanting a way to convert a .NET Stream to a Windows Runtime IRandomAccessStream. Let’s just call it an AsRandomAccessStream extension method. We weren't able to get this feature into Windows 8, but it was one of our first additions to Windows 8.1 Preview.
You can now write the following code, to download an image with HttpClient, load it in a BitmapImage and then set as the source for a Xaml Image control.
//access image via networking i/o
var imageUrl = "http://www.microsoft.com/global/en-us/news/publishingimages/logos/MSFT_logo_Web.jpg";
var client = new HttpClient();
Stream stream = await client.GetStreamAsync(imageUrl);
var memStream = new MemoryStream();
await stream.CopyToAsync(memStream);
memStream.Position = 0;
var bitmap = new BitmapImage();
bitmap.SetSource(memStream.AsRandomAccessStream());
image.Source = bitmap;
HTH.
Convert Stream to IRandomAccessStream
There is an extension method for that:
Stream stream = GetSomeStream();
IRandomAccessStream randomAccessStream = stream.AsRandomAccessStream();
Just make sure that you have using System.IO
at the top of your code file.
C# UWP Converting from System.IO.Stream to Windows.Storage.Streams.IRandomAccessStreamWithContentType
From your code, it seems you have used BitmapDecoder
. The BitmapDecoder
provides read access to bitmap container data as well as data from the first frame.
We should be able to create a new InMemoryRandomAccessStream
for the encoder to write to and call BitmapEncoder.CreateForTranscodingAsync
, passing in the in-memory stream and the decoder object.
For example:
Windows.Storage.Streams.IRandomAccessStream random = await Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/sunset.jpg")).OpenReadAsync();
Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(random);
Windows.Graphics.Imaging.PixelDataProvider pixelData = await decoder.GetPixelDataAsync();
byte[] buffer = pixelData.DetachPixelData();
InMemoryRandomAccessStream inMemoryRandomAccessStream = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryRandomAccessStream, decoder);
encoder.BitmapTransform.ScaledWidth = 320;
encoder.BitmapTransform.ScaledHeight = 240;
await encoder.FlushAsync();
inMemoryRandomAccessStream.Seek(0);
random.Seek(0);
BitmapImage bitmapImage = new BitmapImage();
RandomAccessStreamReference iReferenceStream = RandomAccessStreamReference.CreateFromStream(inMemoryRandomAccessStream);
IRandomAccessStreamWithContentType newStream = await iReferenceStream.OpenReadAsync();
bitmapImage.SetSource(newStream);
MyImage.Source = bitmapImage;
IRandomAccessStream does not support the CloneStream method because it requires cloning and this stream does not support cloning
Someone already answered a similar question in:
Is there a way to convert a System.IO.Stream to a Windows.Storage.Streams.IRandomAccessStream?
This code solves the problem:
private static async Task<IRandomAccessStreamReference> ConvertToRandomAccessStream(MemoryStream memoryStream)
{
var randomAccessStream = new InMemoryRandomAccessStream();
var outputStream = randomAccessStream.GetOutputStreamAt(0);
await RandomAccessStream.CopyAndCloseAsync(memoryStream.AsInputStream(), outputStream);
var result = RandomAccessStreamReference.CreateFromStream(randomAccessStream);
return result;
}
save stream to file in c# and winrt
The IRandomAccessStream has a method called GetInputStreamAt http://msdn.microsoft.com/en-US/library/windows/apps/windows.storage.streams.irandomaccessstream
IInputStream inputStream = stream.GetInputStreamAt(0);
This gets you an IInputStream.
The IInputStream interface defines just one method, ReadAsync, which lets you read bytes into an IBuffer object. Windows.Storage.Stream also includes a DataReader class that you create based on an IInputStream object and then read numerous .NET objects from the stream as well as arrays of bytes. http://www.charlespetzold.com/blog/2011/11/080203.html , http://msdn.microsoft.com/library/windows/apps/BR208119
using (var stream = new InMemoryRandomAccessStream())
{
// for example, render pdf page
var pdfPage = document.GetPage((uint)i);
await pdfPage.RenderToStreamAsync(stream);
// then, write page to file
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
var buffer = new byte[(int)stream.Size];
reader.ReadBytes(buffer);
await Windows.Storage.FileIO.WriteBytesAsync(file, buffer);
}
}
now you have a buffer containing all the read bytes.
you can now save this buffer to a file http://blog.jerrynixon.com/2012/06/windows-8-how-to-read-files-in-winrt.html
var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("MyWav.wav", Windows.Storage.CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteBytesAsync(file, buffer);
Is there a way to convert an IAsyncOperation to System.IO.Steam?
Check if this works:
Stream fs = (await temp[i].OpenAsync(FileAccessMode.Read)).AsStream();
You have all the information in your error message - OpenAsync
returns (after you await
it) IRandomAccessStream
, you can convert it to System.IO.Stream
with AsStream method.
Getting a Stream from a resource file / content
Ok I found it!
StorageFile storageFile =
await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
var randomAccessStream = await storageFile.OpenReadAsync();
Stream stream = randomAccessStream.AsStreamForRead();
Related Topics
Setting Up Swagger (ASP.NET Core) Using the Authorization Headers (Bearer)
Overriding Fields or Properties in Subclasses
C# - How to Make Two Forms Reference Each Other
Differencebetween Iequalitycomparer<T> and Iequatable<T>
How to Specify Mapping Rule When Names of Properties Differ
How to Make Ef-Core Use a Guid Instead of String for Its Id/Primary Key
Writing to Output Window of Visual Studio
How to Highlight Wrapped Text in a Control Using the Graphics
Httpcontext.Current Is Null When Unit Test
How to Get the List of All Printers in Computer
Sending Sms from an ASP.NET Website
Automatic Cookie Handling C#/.Net Httpwebrequest+Httpwebresponse
What Does Linq Return When the Results Are Empty
How to Use Async to Increase Winforms Performance
Button in a Column, Getting the Row from Which It Came on the Click Event Handler