标题: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");
}
}

C#压缩和解压缩字节(GZip)的更多相关文章

  1. Linux下的压缩和解压缩命令——gzip/gunzip

    gzip命令 gzip命令用来压缩文件.gzip是个使用广泛的压缩程序,文件经它压缩过后,其名称后面会多处".gz"扩展名. gzip是在Linux系统中经常使用的一个对文件进行压 ...

  2. java工具类——java将一串数据按照gzip方式压缩和解压缩

    我要整理在工作中用到的工具类分享出来,也方便自己以后查阅使用,这些工具类都是我自己实际工作中使用的 import java.io.ByteArrayInputStream; import java.i ...

  3. Linux下的压缩和解压缩命令gzip/gunzip

    作者:邓聪聪 Linux下的压缩和解压缩命令——gzip/gunzip yum -y install zip gzip (--安装压缩工具) gzip命令 gzip命令用来压缩文件.gzip是个使用广 ...

  4. .net 利用 GZipStream 压缩和解压缩

    1.GZipStream 类 此类在 .NET Framework 2.0 版中是新增的. 提供用于压缩和解压缩流的方法和属性 2.压缩byte[] /// <summary> /// 压 ...

  5. 使用commons-compress操作zip文件(压缩和解压缩)

    http://www.cnblogs.com/luxh/archive/2012/06/28/2568758.html Apache Commons Compress是一个压缩.解压缩文件的类库. 可 ...

  6. 利用SharpZipLib进行字符串的压缩和解压缩

    http://www.izhangheng.com/sharpziplib-string-compression-decompression/ 今天搞了一晚上压缩和解压缩问题,java压缩的字符串,用 ...

  7. Linux常用命令学习3---(文件的压缩和解压缩命令zip unzip tar、关机和重启命令shutdown reboot……)

    1.压缩和解压缩命令    常用压缩格式:.zip..gz..bz2..tar.gz..tar.bz2..rar .zip格式压缩和解压缩命令        zip 压缩文件名 源文件:压缩文件   ...

  8. 关于webservice大数据量传输时的压缩和解压缩

    当访问WebSerivice时,如果数据量很大,传输数据时就会很慢.为了提高速度,我们就会想到对数据进行压缩.首先我们来分析一下. 当在webserice中传输数据时,一般都采用Dataset进行数据 ...

  9. 在C#中利用SharpZipLib进行文件的压缩和解压缩收藏

    我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net(http://www.icsharpcode.net/OpenSource/SharpZipL ...

随机推荐

  1. Upload图片-单张

    上传图片全不怕,轻松实现图片上传, 可以实现显示缩略图喔: 后台代码: protected void btnpic_upload_Click(object sender, EventArgs e) { ...

  2. JavaScript DOM编程艺术(第2版)学习笔记2(4~6章应用实例)

    本书的第4章使用第3章学到的操作DOM的方法和属性写了一个展示图片的网页,并在第5,6章对代码进行了优化. 第一版,搭建网页的静态结构,包括一级标题<h1>,无序列表清单<ul> ...

  3. Linux crontab 定时任务设置

    第1列分钟1-59第2列小时1-23(0表示子夜)第3列日1-31第4列月1-12第5列星期0-6(0表示星期天)第6列要运行的命令 下面是crontab的格式:分 时 日 月 星期 要运行的命令 这 ...

  4. Win7下安装Flash低版本

    我把HKEY_LOCAL_MACHINE\SOFTWARE\Macromedia\FlashPlayer\SafeVersions中高于要装的版本的项目都删了,还是不行. 看了这个帖子后发现,原来64 ...

  5. day20 匿名函数,内置函数,面向过程编程

    目录 有名函数 匿名函数 max() min() sorted map filter 内置函数 面向过程编程 有名函数 def f1(): print('my name is f1') f1() my ...

  6. epoll的边缘触发与水平触发

    epoll的边缘触发与水平触发 Tcp连接是双向的,内核为每个socket维护两个缓冲区,读缓冲区与写缓冲区,内核会一个关注这两个缓冲区,当采用水平触发时,对于写缓冲区而言,如果有多余空间可写,对于读 ...

  7. [spoj] HIGH - Highways (生成树计数)

    传送门 输入格式: 第一行一个整数T,表示测试数据的个数 每个测试数据第一行给出 n,m 分别表示点数与边数 接下来 m 行,每行给出两个数 a,b ,表示 a,b 之间有一条无向边 输出格式: 每个 ...

  8. UNIX系统高级编程——第四章-文件和目录-总结

    文件系统: 以UNIX系统V文件系统为例: 磁盘分为区,每个分区都有自己的文件系统: ​ i节点是固定长度的记录项,包含了文件的相关信息.目录项包含文件名和i节点号.stat结构中除文件名和i节点编号 ...

  9. qml与c++混合编程

    QML 与 C++ 混合编程内容:1. QML 扩展2. C++ 与 QML 交互3. 开发时要尽量避免使用的 QML 元素4. demo 讲解5. QML 语法C++ 与 QML 的交互是通过注册 ...

  10. JavaScript变量提升(Hoisting)的小案例

    变量提升(Hoisting)的小案例 执行以下代码的结果是什么?为什么? 答案 这段代码的执行结果是undefined 和 2. 这个结果的原因是,变量和函数都被提升(hoisted) 到了函数体的顶 ...