' System.IO.InvalidDataException'在Stream.Read操作中

时间:2018-04-17 09:03:34

标签: c# utf-8 stream decode encode

我正在使用deflate压缩技术压缩json并保存到sql server数据库。 json包含来自任何文化的价值,即。 th-TH,zh-TW。压缩的字符串将成功保存在数据库中。

Json包含的数据包括 {" @ id":" 2113"," description":"อาหารเช้าคอนติเนนทั ล"}

现在当我从db读取相同的数据时,我将其转换为字节为 Encoding encoding = Encoding.UTF8; encoding.GetBytes(data ?? string.Empty)

像这样的压缩

public static string Compress(this string data, CompressionTypeOptions compressionType)
    {                           
            var bytes = Compress(Encoding.UTF-8.GetBytes(data ?? string.Empty), compressionType);
            return Encoding.UTF-8.GetString(bytes);
        }          
    }

private static byte[] Compress(byte[] data, CompressionTypeOptions compressionType)
    {            
        using (var memoryStream1 = new MemoryStream(data))
        {
            using (var memoryStream2 = new MemoryStream())
            {
                using (var compressionStream = CreateCompressionStream(compressionType, (Stream)memoryStream2,
                                                                    CompressionMode.Compress))
                {
                    CopyTo((Stream)memoryStream1, compressionStream);
                    compressionStream.Close();
                    return memoryStream2.ToArray();
                }
            }
        }
    }

然后像这样解压缩

using (var memoryStream = new MemoryStream(data))
        {
            using (var compressionStream = CreateCompressionStream(compressionType, (Stream)memoryStream,
                                                                           CompressionMode.Decompress))
                return ReadAllBytesFromStream(compressionStream);
        }

这是ReadAllBytesFromStream定义

private static byte[] ReadAllBytesFromStream(Stream stream)
    {

        using (var memoryStream = new MemoryStream())
        {
            var buffer1 = new byte[1];
            while (true)
            {
                int count = stream.Read(buffer1, 0, 1);
                if (count != 0)
                    memoryStream.Write(buffer1, 0, count);
                else
                    break;
            }
            var length = memoryStream.Length;
            var buffer2 = new byte[length];
            memoryStream.Position = 0L;
            memoryStream.Read(buffer2, 0, (int)length);
            return buffer2;
        }

    }

int count = stream.Read(buffer1, 0, 1);获取错误 ' System.IO.InvalidDataException' '未知块类型。流可能已损坏。'

任何帮助都是适用的

0 个答案:

没有答案