Metro app中使用内存流压缩和解压

以前使用MemoryStream和DeflateStream进行压缩解压的操作,在Metro app中同样的代码不能执行了,winRT中提供了对应的封闭类,修改如下

        public static async Task<string> Compress(string strSource)

        {

            byte[] bytCompressed;

            using (var ms = new InMemoryRandomAccessStream())

            {

                byte[] buffer = Encoding.UTF8.GetBytes(strSource);

                IBuffer iBuffer = buffer.AsBuffer();

                using (var stream = new Compressor(ms.GetOutputStreamAt(0)))

                {

                    await stream.WriteAsync(iBuffer);

                    await stream.FlushAsync();

                    await stream.FinishAsync();

                    ms.Seek(0);

                    bytCompressed = new byte[ms.Size];



                    await ms.AsStream().ReadAsync(bytCompressed, 0, bytCompressed.Length);

                }

            }

            return Convert.ToBase64String(bytCompressed);

        }



        public static async Task<string> Decompress(string strSource)

        {

            string ret = string.Empty;

            using (var ms = new InMemoryRandomAccessStream())

            {

                byte[] byt = Convert.FromBase64String(strSource);

                await ms.WriteAsync(byt.AsBuffer());

                Decompressor stream = new Decompressor(ms.GetInputStreamAt(0));

                byte[] buffer = new byte[10000];

                IBuffer iBuffer = buffer.AsBuffer();

                var buff = await stream.ReadAsync(iBuffer, iBuffer.Length, InputStreamOptions.None);

                byte[] byts = buff.ToArray();

                ret = Encoding.UTF8.GetString(byts, 0, byts.Length);

            }

            return ret;

        }

你可能感兴趣的:(metro)