有没有办法将 System.IO.Stream 转换为 Windows.Storage.Streams.IRandomAccessStream? [英] Is there a way to convert a System.IO.Stream to a Windows.Storage.Streams.IRandomAccessStream?

查看:18
本文介绍了有没有办法将 System.IO.Stream 转换为 Windows.Storage.Streams.IRandomAccessStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows 8 中;我想将 MemoryStream 的内容传递给接受 Windows.Storage.Streams.IRandomAccessStream 类型参数的类.有什么方法可以将此 MemoryStream 转换为 IRandomAccessStream?

In Windows 8; I would like to pass the contents of a MemoryStream to a class that accepts a parameter of type Windows.Storage.Streams.IRandomAccessStream. Is there any way to convert this MemoryStream to an IRandomAccessStream?

推荐答案

要使用扩展:必须添加using System.IO"

To use the extensions: you must add "using System.IO"

在 Windows8 中,.NET 和 WinRT 类型通常在后台转换为兼容类型/从兼容类型转换,因此您不必关心它.

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.

但是,对于流,有一些帮助方法可以在 WinRT 和 .NET 流之间进行转换:用于从 WinRT 流转换 ->.NET 流:

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

用于从 .NET 流转换 ->WinRT 流:

For converting from .NET streams -> WinRT streams:

Windows.Storage.Streams.IInputStream inStream = stream.AsInputStream();
Windows.Storage.Streams.IOutputStream outStream = stream.AsOutputStream();

更新:2013-09-01

不要说微软不听它的开发者社区;)

Let it not be said that Microsoft doesn't listen to it's developer community ;)

.NET FX 4.5.1 的公告,微软声明:

你们中的许多人一直想要一种将 .NET 流转换为 Windows 运行时 IRandomAccessStream 的方法.让我们称之为 AsRandomAccessStream 扩展方法.我们无法将此功能添加到 Windows 8 中,但它是我们首次添加到 Windows 8.1 Preview 中的功能之一.

您现在可以编写以下代码,使用 HttpClient 下载图像,将其加载到 BitmapImage 中,然后设置为 Xaml Image 控件的源.

    //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.

这篇关于有没有办法将 System.IO.Stream 转换为 Windows.Storage.Streams.IRandomAccessStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆