简体   繁体   English

如何从windows8商店应用程序中的字节数组中获取流

[英]How to get a stream from a byte array in a windows8 store app

I have been trying get a stream from a byte array in metro style app using the following code. 我一直在尝试使用以下代码从metro风格应用程序中的字节数组中获取流。

InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();
memoryStream.AsStreamForWrite().Write(byteArray, 0, byteArray.Length);
memoryStream.Seek(0);

It executes with no errors but stream size is zero (0). 它执行时没有错误,但流大小为零(0)。 Can anybody tell me why is its size is zero? 谁能告诉我为什么它的尺寸为零?

You can use the DataWriter and DataReader classes. 您可以使用DataWriterDataReader类。 For example ... 例如 ...

// put bytes into the stream
var ms = new InMemoryRandomAccessStream();
var dw = new Windows.Storage.Streams.DataWriter(ms);
dw.WriteBytes(new byte[] { 0x00, 0x01, 0x02 });
await dw.StoreAsync();

// read them out
ms.Seek(0);
byte[] ob = new byte[ms.Size];
var dr = new Windows.Storage.Streams.DataReader(ms);
await dr.LoadAsync((uint)ms.Size);
dr.ReadBytes(ob);

You can also use the BinaryWriter/BinaryReader to read and write from and to byte[] and Streams. 您还可以使用BinaryWriter / BinaryReader来读取和写入byte []和Streams。

    private Stream ConvertToStream(byte[] raw)
    {
        Stream streamOutput = new MemoryStream();
        using (BinaryWriter writer = new BinaryWriter(streamOutput))
        {
            writer.Write(raw);
        }
        return streamOutput;
    }

Another option is to use built in extension methods as Marc Gravell already mentioned: 另一种选择是使用内置的扩展方法,如Marc Gravell已经提到的:

    private Stream ConvertToStream(byte[] raw)
    {
        return raw.AsBuffer().AsStream();
    }

The extension methods are commented with [Security Critical] which may indicate a later change. 扩展方法用[Security Critical]评论,这可能表示稍后的更改。 However, after looking around a bit I couldn't find any additional information on the security code comment. 但是,在环顾四周之后,我找不到有关安全代码注释的任何其他信息。

I know this is a very old question, but I was running into this issue myself today and figured it out so I'll leave this here for others. 我知道这是一个非常古老的问题,但是我今天自己也遇到了这个问题,并且想出来了,所以我会把它留给其他人。

I realized that the stream wasn't being written if it was too small. 我意识到如果它太小的话就没有写入流。 To fix this, I explicitly set the length of the stream like this: 为了解决这个问题,我明确地设置了流的长度,如下所示:

ms.AsStreamForWrite(imageBytes.Length).Write(imageBytes, 0, imageBytes.Length);

That should be all you need. 这应该就是你所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM