WinRT中的流和.NET中的Stream的相互转换以及DataReader,DataWriter用法

      随着Windows8的发布,微软给出了一个Windows Runtime(以下简称WinRT),据说是用COM技术实现的。在结合使用.NET和WinRT时,你会发现它们对相同的概念,有不同的实现,或者说是类,比如异步操作,.NET中用Task概念,而WinRT则是用IAsyncInfo,IAsyncAction等,而在流的概念中,.NET围绕Stream类建立,而WinRT则先定义了三个主要的接口,然后逐一实现之。本文就是集中在“流”的相互转换上,因为你在编写Metro App时,会用到WinRT组件。

      首先,.NET的Stream可谓是集读、写以及流定位于一身的一个类,那么在WinRT中则将它抽象成三个不同的接口,分别为:IInputStream、IOutupStream和IRandomAccessStream,其实这三个接口就是对应Stream所提供的功能。当然还有别的接口,这里暂不介绍。还有一个要介绍的是IBuffer,这个接口提供了对我们传统放置字节数组的byte[]的抽象,而且只提供了Capcity和Length两个属性(没有方法),Capcity是说这个IBuffer能够容纳多少字节,而Length则说明实际有多少字节,WinRT中也会有一个实现了该接口的类,称为Buffer,我们使用输入输出流时,都会用到。

     然后,我们在转换时,最好加入System.IO命名空间,这个空间提供了我们需要的转换的扩展方法。

1. 将IBuffer转换成一个.NET Stream:

由于已经知道了一个字节块(IBuffer),那么我们可以把它放入到一个内存的随机访问流中,就是从Buffer中读取byte到内存流中(InMemoryRandomAccessStream,它实现了上诉的三大接口),再通过扩展方法转换成Stream,代码如下

 InMemoryRandomAccessStream memoryStremWRT = new InMemoryRandomAccessStream();
            await memoryStremWRT.ReadAsync(buffer,buffer.Length,InputStreamOptions.None);
            Stream stream = memoryStremWRT.AsStream();

 2.将一个IOutputStream转换成为Stream:

 stream = outputStream.AsStreamForWrite();

 

3.将一个IInputStream转换成Stream:

 stream = inputStream.AsStreamForRead();

 

4.将IRandomAccess转换成Stream:

stream=randomAccess.AsStream();

 

5.Stream 转成Buffer:

由于buffer需要读取数据,所以要一个输入流,此处使用DataReader来加载,它的构造参数就是一个输入流。

IBuffer buffer=null;
var inputstream=stream.AsInputStream();
using(var dataReader=new DataReader(inputstream))
{
      await dataReader.LoadAsync((uint)stream.Length);
      buffer=dataReader.DetachBuffer();
}

 

6.Stream 转成IIputStream

var inputstream=stream.AsInputStream();

 

7.Stream转成IOutputStream

var outputstream=stream.AsOutputStream();

8.Stream转成 IRandomAccess:

此处没有直接提供扩展方法,所以我们的思路还是先构造出一个输入流来获取数据:

IBuffer buffer=null;
var inputstream=stream.AsInputStream();
using(var dataReader=new DataReader(inputstream))
{
      await dataReader.LoadAsync((uint)stream.Length);
      buffer=dataReader.DetachBuffer();
}
var randomAccessStream =new InMemoryRandomAccessStream ();
await randomAccessStream.WriteAsync(buffer);

 

 

以上用到了DataReader类,对应的还有DataWriter类,这两个类和.NET中的StreamReader和StreamWriter的用法和概念一样,使用了适配器模式,将我们平时用到的类型,比如文本啊,整形数据啊,输入到流或者从流中读出,那么底层的字符,或者整形与byte之间的转换就不需要我们操心了,最多我们要指明是用大端还是小端表示,或者使用什么字节编码。

      对于DataReader的含义,就是说我们要从一个输入流中读取数据(数据源是输入流,目标是从流中组装的具体变量值),至于数据的具体含义,那么就看你自己的需求了,一般情况下你是知道流到底是应该编码成string,还是组成int,long,亦或是两者都有,只要顺序搞对就行。

      对于DataWriter的含义,则与Reader相对,就是我们输入我们需要的数据,无论是byte,还是string 还是int,long,经过适度的编码以及分解,然后输出到一个流中。

以上的参考代码如下:

 // Initialize the in-memory stream where data will be stored.
    using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
    {
        // Create the data writer object backed by the in-memory stream.
        using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream))
        {
            dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

            // Parse the input stream and write each element separately.
            string[] inputElements = ElementsToWrite.Text.Split(';');
            foreach (string inputElement in inputElements)
            {
                uint inputElementSize = dataWriter.MeasureString(inputElement);
                dataWriter.WriteUInt32(inputElementSize);
                dataWriter.WriteString(inputElement);
            }

            // Send the contents of the writer to the backing stream.
            await dataWriter.StoreAsync();

            // For the in-memory stream implementation we are using, the flushAsync call 
            // is superfluous,but other types of streams may require it.
            await dataWriter.FlushAsync();

            // In order to prolong the lifetime of the stream, detach it from the 
            // DataWriter so that it will not be closed when Dispose() is called on 
            // dataWriter. Were we to fail to detach the stream, the call to 
            // dataWriter.Dispose() would close the underlying stream, preventing 
            // its subsequent use by the DataReader below.
            dataWriter.DetachStream();
        }

        // Create the input stream at position 0 so that the stream can be read 
        // from the beginning.
        using (var inputStream = stream.GetInputStreamAt(0))
        {
            using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))
            {
                // The encoding and byte order need to match the settings of the writer 
                // we previously used.
                dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                dataReader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                // Once we have written the contents successfully we load the stream.
                await dataReader.LoadAsync((uint)stream.Size);

                var receivedStrings = "";

                // Keep reading until we consume the complete stream.
                while (dataReader.UnconsumedBufferLength > 0)
                {
                    // Note that the call to readString requires a length of "code units" 
                    // to read. This is the reason each string is preceded by its length 
                    // when "on the wire".
                    uint bytesToRead = dataReader.ReadUInt32();
                    receivedStrings += dataReader.ReadString(bytesToRead) + "\n";
                }

                // Populate the ElementsRead text block with the items we read 
                // from the stream.
                ElementsRead.Text = receivedStrings;
            }
        }

 

你可能感兴趣的:(WinRT,Windows,8,c#,runtime)