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

前端 未结 3 927
南旧
南旧 2021-01-16 01:02

I have been trying get a stream from a byte array in metro style app using the following code.

InMemoryRandomAccessStream memoryStream = new InMemoryRandomAc         


        
相关标签:
3条回答
  • 2021-01-16 01:42

    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.

    0 讨论(0)
  • 2021-01-16 01:45

    You can use the DataWriter and DataReader classes. 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);
    
    0 讨论(0)
  • 2021-01-16 01:55

    You can also use the BinaryWriter/BinaryReader to read and write from and to byte[] and 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:

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

    The extension methods are commented with [Security Critical] which may indicate a later change. However, after looking around a bit I couldn't find any additional information on the security code comment.

    0 讨论(0)
提交回复
热议问题