17

这是从资源文件中获取Stream的正确/唯一方法吗?

    Uri uri = new Uri(fullPath);

    StorageFile storageFile = 
      await Windows.Storage.StorageFile.
        GetFileFromApplicationUriAsync(uri);

    IRandomAccessStreamWithContentType randomAccessStream = 
      await storageFile.OpenReadAsync();

    IInputStream resourceStream = (IInputStream)
      randomAccessStream.GetInputStreamAt(0);

我所有的其他源(http 和本地存储)都返回一个 Stream 对象,并且不得不使用使用其中一个或另一个的 if-else 代码是很痛苦的。

我也尝试从中创建一个 MemoryStream ,但我什至找不到将字节取出的方法......请帮忙。

    uint size = (uint)randomAccessStream.Size;
    IBuffer buffer = new Windows.Storage.Streams.Buffer(size);
    await randomAccessStream.ReadAsync(buffer, size, 
      InputStreamOptions.None);

    Stream stream = new MemoryStream(buffer); // error takes byte[] not IBuffer

从资源读取时的 IInputStream.ReadAsync():http: //msdn.microsoft.com/en-us/library/windows/apps/windows.storage.streams.iinputstream.readasync.aspx

而 Stream.Read() 和 Stream.ReadAsync() 看起来像这样:

http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx

http://msdn.microsoft.com/en-us/library/hh137813.aspx

谢谢

4

2 回答 2

30

好的,我找到了!

    StorageFile storageFile =
      await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);

    var randomAccessStream = await storageFile.OpenReadAsync();
    Stream stream = randomAccessStream.AsStreamForRead();
于 2012-12-14T08:11:17.610 回答
9

您也可以少写一行:

Stream stream = await storageFile.OpenStreamForReadAsync(); 
于 2015-05-05T18:03:21.280 回答