【问题标题】:Getting a Stream from a resource file / content从资源文件/内容中获取流
【发布时间】:2012-12-01 03:16:43
【问题描述】:

这是从资源文件中获取 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

谢谢

【问题讨论】:

    标签: c# asynchronous microsoft-metro windows-runtime windows-store-apps


    【解决方案1】:

    好的,我找到了!

        StorageFile storageFile =
          await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
    
        var randomAccessStream = await storageFile.OpenReadAsync();
        Stream stream = randomAccessStream.AsStreamForRead();
    

    【讨论】:

    • 是否可以将流转换为 StorageFile? :o
    • 非常感谢...你让我很开心 :) 早些时候尝试做 randomAccessStream --> Byte[] --> memorystream 但它不能正常工作。总是在 DataReader.LoadAsync((uint)s.Size); 下面的行上失败 IRandomAccessStream --> Byte[];现在像魅力一样工作
    【解决方案2】:

    你也可以少一行:

    Stream stream = await storageFile.OpenStreamForReadAsync(); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 2011-05-22
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多