当前位置: 移动技术网 > IT编程>开发语言>c# > C#自定义字符串压缩和解压缩的方法

C#自定义字符串压缩和解压缩的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#自定义字符串压缩和解压缩的方法。分享给大家供大家参考。具体如下:

class ziplib
{
 public static string zip(string value)
 {
  //transform string into byte[] 
  byte[] bytearray = new byte[value.length];
  int indexba = 0;
  foreach (char item in value.tochararray())
  {
 bytearray[indexba++] = (byte)item;
  }
  //prepare for compress
  system.io.memorystream ms = new system.io.memorystream();
  system.io.compression.gzipstream sw = new system.io.compression.gzipstream(ms,
 system.io.compression.compressionmode.compress);
  //compress
  sw.write(bytearray, 0, bytearray.length);
  //close, do not flush cause bytes will go missing...
  sw.close();
  //transform byte[] zip data to string
  bytearray = ms.toarray();
  system.text.stringbuilder sb = new system.text.stringbuilder(bytearray.length);
  foreach (byte item in bytearray)
  {
 sb.append((char)item);
  }
  ms.close();
  sw.dispose();
  ms.dispose();
  return sb.tostring();
 }
 public static string unzip(string value)
 {
  //transform string into byte[]
  byte[] bytearray = new byte[value.length];
  int indexba = 0;
  foreach (char item in value.tochararray())
  {
 bytearray[indexba++] = (byte)item;
  }
  //prepare for decompress
  system.io.memorystream ms = new system.io.memorystream(bytearray);
  system.io.compression.gzipstream sr = new system.io.compression.gzipstream(ms, system.io.compression.compressionmode.decompress);
  //reset variable to collect uncompressed result
  bytearray = new byte[bytearray.length];
  //decompress
  int rbyte = sr.read(bytearray, 0, bytearray.length);
  //transform byte[] unzip data to string
  system.text.stringbuilder sb = new system.text.stringbuilder(rbyte);
  //read the number of bytes gzipstream red and do not a for each bytes in
  //resultbytearray;
  for (int i = 0; i < rbyte; i++)
  {
 sb.append((char)bytearray[i]);
  }
  sr.close();
  ms.close();
  sr.dispose();
  ms.dispose();
  return sb.tostring();
 }
}

代码使用方法:

string str_org="aaaaaaaaaabbbbbbbbbbbbcccccccccdddddddd";
string str_comp = ziplib.zip(str_org);
console.writeline("str_comp:" + str_comp);
string str_uncomp = ziplib.unzip(str_comp);
console.writeline("str_uncomp:" + str_uncomp);
console.readline();

希望本文所述对大家的c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网