标题:C#压缩和解压缩字节(GZip的使用)

作用:此类在 .NET Framework 2.0 版中是新增的。提供用于压缩和解压缩流的方法和属性。
定义:表示 GZip 数据格式,它使用无损压缩和解压缩文件的行业标准算法。这种格式包括一个检测数据损坏的循环冗余校验值。GZip 数据格式使用的算法与 DeflateStream 类的算法相同,但它可以扩展以使用其他压缩格式。这种格式可以通过不涉及专利使用权的方式轻松实现。gzip 的格式可以从 RFC 1952“GZIP file format specification 4.3(GZIP 文件格式规范 4.3)GZIP file format specification 4.3(GZIP 文件格式规范 4.3)”中获得。此类不能用于压缩大于 4 GB 的文件。

下面给出两个具体Demo:
实例1

//压缩字节
//1.创建压缩的数据流
//2.设定compressStream为存放被压缩的文件流,并设定为压缩模式
//3.将需要压缩的字节写到被压缩的文件流
public static byte[] CompressBytes(byte[] bytes)
{
using(MemoryStream compressStream = new MemoryStream())
{
using(var zipStream = new GZipStream(compressStream, CompressMode.ComPress))
zipStream.Write(bytes, , bytes.Length);
return compressStream.ToArray();
}
}
//解压缩字节
//1.创建被压缩的数据流
//2.创建zipStream对象,并传入解压的文件流
//3.创建目标流
//4.zipStream拷贝到目标流
//5.返回目标流输出字节
public static byte[] Decompress(byte[] bytes)
{
using(var compressStream = new MemoryStream(bytes))
{
using(var zipStream = new GZipStream(compressStream, CompressMode.DeCompress))
{
using(var resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
return resultStream.ToArray();
}
}
}
}

实例2(摘自MSDN):

class Program
{
public static int ReadAllBytesFromStream(Stream stream, byte[] buffer)
{
int offset = ;
int totalCount = ;
while (true)
{
int bytesRead = stream.Read(buffer, offset, );
if (bytesRead == )
{
break;
}
offset += bytesRead;
totalCount += bytesRead;
}
return totalCount;
} public static bool CompareData(byte[] buf1, int len1, byte[] buf2, int len2)
{
if (len1 != len2)
{
Console.WriteLine("Number of bytes in two buffer are diffreent {0}:{1}", len1, len2);
return false;
}
for (int i = ; i < len1; i++)
{
if (buf1[i] != buf2[i])
{
Console.WriteLine("byte {0} is different {1}{2}", i, buf1[i], buf2[i]);
return false;
}
}
Console.WriteLine("All byte compare true");
return true;
} public static void GZipCompressDecompress(string fileName)
{
Console.WriteLine("Test compresssion and decompression on file {0}", fileName);
FileStream infile;
try
{
//Comopress
infile = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] buffer = new byte[infile.Length];
int count = infile.Read(buffer, , buffer.Length);
if (count != buffer.Length)
{
infile.Close();
infile.Dispose();
Console.WriteLine("Test Failed: Unable to read data from file");
return;
}
infile.Close();
MemoryStream ms = new MemoryStream();
GZipStream compressGZipStream = new GZipStream(ms, CompressionMode.Compress, true);
Console.WriteLine("Compression");
compressGZipStream.Write(buffer, , buffer.Length); //从指定字节数组中将压缩的字节写入基础流
compressGZipStream.Close();
Console.WriteLine("Original size:{0}, Compressed size:{1}", buffer.Length, ms.ToArray().Length); //DeCompress
ms.Position = ;
GZipStream deCompressGZipStream = new GZipStream(ms, CompressionMode.Decompress);
Console.WriteLine("Decompression");
byte[] decompressedBuffer = new byte[buffer.Length + ]; int totalCount = ReadAllBytesFromStream(deCompressGZipStream, decompressedBuffer);
Console.WriteLine("Decompressed {0} bytes", totalCount); if (!CompareData(buffer, buffer.Length, decompressedBuffer, decompressedBuffer.Length))
{
Console.WriteLine("Error. The two buffers did not compare.");
}
deCompressGZipStream.Dispose();
}
catch (ArgumentNullException)
{
Console.WriteLine("ArgumentNullException:{0}", "Error: The path is null.");
}
catch (ArgumentException)
{
Console.WriteLine("ArgumentException:{0}", "Error: path is a zero-length string, contains an empty string or one more invlaid characters");
}
catch (NotSupportedException)
{
Console.WriteLine("NotSupportedException:{0}", "Cite no file, such as 'con:'、'com1'、'lpt1' in NTFS");
}
catch (FileNotFoundException)
{
Console.WriteLine("FileNotFoundException:{0]", "Find no file");
}
catch (IOException)
{
Console.WriteLine("IOException:{0}", "Occur I/O error");
}
catch (System.Security.SecurityException)
{
Console.WriteLine("System.Security.SecurityException{0}:", "The calls has no permission");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("UnauthorizedAccessException:{0}", "path specified a file that is read-only, the path is a directory, " +
"or caller does not have the required permissions");
}
} static void Main(string[] args)
{
GZipCompressDecompress(@"D:\config.ini");
}
}

最新文章

  1. JavaScript权威设计--JavaScript函数(简要学习笔记十)
  2. Java学习笔记(04)
  3. QuickFlow UI 控件之 NamedFormAttachment
  4. Jsp与servlet本质上的区别
  5. 【转】使用jquery animate创建平滑滚动效果
  6. css实现阴影效果(box-shadow)
  7. exit(0)与exit(1)、return区别
  8. 初级jQuery的使用
  9. loadrunner_analysis技巧_filter和group by
  10. Python文件中文编码问题
  11. MVC 和 MVVM
  12. oracle状态
  13. maven系列--eclipse的m2插件
  14. UNIX网络编程——通用套接字选项
  15. 蚂蚁爬杆问题js实现
  16. C#字符串的CompareTo比较,让我疑惑的地方
  17. uboot中获取dts资源并操作gpio口
  18. docker 学习(九) docker部署静态网站
  19. C++各种类继承关系的内存布局
  20. UVa 11542 Square (高斯消元)

热门文章

  1. Hua Wei 机试题目二
  2. USACO 保护花朵 Protecting the Flowers, 2007 Jan
  3. 多帧图片转gif
  4. iOS-Core-Animation-Advanced-Techniques/12-性能调优/性能调优.md
  5. 中国人自己的技术!百度开源自研底层区块链XuperChain
  6. 使用CablleStatement调用存储过程
  7. HDU 1558 Segment set( 判断线段相交 + 并查集 )
  8. 三、Git 分支
  9. Linux下安装Solr7.5.0,并部署到Tomcat
  10. 论文阅读《ActiveStereoNet:End-to-End Self-Supervised Learning for Active Stereo Systems》