日期:2014-05-18  浏览次数:21055 次

C# 用System.IO.Compression.DeflateStream压缩/解压字符串的问题。。
写了两个方法,用.net 自带的System.IO.Compression.DeflateStream类进行【字符串】的压缩和解压。
(一)压缩:
  public static string Compress(string strSource)
  {
  System.Text.Encoding encoding = System.Text.Encoding.Unicode;
  byte[] buffer = encoding.GetBytes(strSource);

  System.IO.MemoryStream ms = new System.IO.MemoryStream();
  System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true);
  stream.Write(buffer, 0, buffer.Length);
  stream.Close();

  buffer = ms.ToArray();
  ms.Close();

  return encoding.GetString(buffer);
  }

(二)解压:
  public static string Decompress(string strSource)
  {
  System.Text.Encoding encoding = System.Text.Encoding.Unicode;
  byte[] buffer = encoding.GetBytes(strSource);

  System.IO.MemoryStream ms = new System.IO.MemoryStream();
  ms.Write(buffer, 0, buffer.Length);
  ms.Position = 0;
  System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress);
  stream.Flush();

  int nSize = 2 * 1024 * 1024;
  byte[] decompressBuffer = new byte[nSize];
  stream.Read(decompressBuffer, 0, nSize); //××××{{ 这里死活不能读,一读就出异常 }}××××
  //int nSizeRead = ReadAllBytesFromStream(stream, decompressBuffer);
  stream.Close();

  return encoding.GetString(decompressBuffer);
  }

从调试结果看,方法一(压缩字符串)执行结果正常。
但到了方法二(解压字符串),红色显示的那一行一定会出现如下异常:
2008-10-29 18:29:31 System.IndexOutOfRangeException: 索引超出了数组界限。
  在 System.IO.Compression.HuffmanTree.CreateTable()
  在 System.IO.Compression.HuffmanTree..ctor(Byte[] codeLengths)
  在 System.IO.Compression.Inflater.DecodeDynamicBlockHeader()
  在 System.IO.Compression.Inflater.Decode()
  在 System.IO.Compression.Inflater.Inflate(Byte[] bytes, Int32 offset, Int32 length)
  在 System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count)
  在 {名字空间省略}.PlanManager.Decompress(String strSource) 位置 {路径省略...}\PlanManager.cs:行号 164

------解决方案--------------------
为什么要转成String而不直接传byte[]?