C# 压缩与解压
在System.IO.Compression
命名空间下框架封装了一些对流进行压缩和解压缩的类。
使用DeflateStream类压缩文件
Console.WriteLine("请输入待压缩文件的完整路径:");
string inputFilePath = Console.ReadLine();
Console.WriteLine("请输入压缩后文件的输出路径:");
string outputFilePath = Console.ReadLine();
using (FileStream instream = new FileStream(inputFilePath, FileMode.Open))
using (FileStream outstream = new FileStream(outputFilePath, FileMode.Create))
using (DeflateStream defstream = new DeflateStream(outstream, CompressionLevel.Optimal))
{
instream.CopyTo(defstream);
}
FileInfo f1 = new FileInfo(inputFilePath), f2 = new FileInfo(outputFilePath);
Console.WriteLine($"压缩前文件大小:{f1.Length}");
Console.WriteLine($"压缩后文件大小:{f2.Length}");
Console.Read();
创建Zip压缩文档
ZipArchive
类支持对zip压缩文档的基本管理,压缩文档中的每个文件由ZipArchiveEntry
类进行维护。Delete
方法可将文件从zip文档中删除;Open
方法将得到一个流实例,可以对压缩文档中的文件实体进行读写。
string zipFile = "demo.zip";
// 生成 zip 文档
if (File.Exists(zipFile))
File.Delete(zipFile);
using (FileStream outfs = File.Create(zipFile))
{
using (ZipArchive zip = new ZipArchive(outfs, ZipArchiveMode.Create))
{
// 第一个文件
ZipArchiveEntry et1 = zip.CreateEntry("docs/doc1.txt");
using (Stream stream = et1.Open())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write("示例文档 A");
}
}
// 第二个文件
ZipArchiveEntry et2 = zip.CreateEntry("docs/doc2.txt");
using (Stream stream = et2.Open())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write("示例文档 B");
}
}
// 第三个文件
ZipArchiveEntry et3 = zip.CreateEntry("docs/doc3.txt");
using (Stream stream = et3.Open())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write("示例文档 C");
}
}
}
}
// 将三个文件解压出来
using(FileStream instream = File.OpenRead(zipFile))
{
using(ZipArchive zip = new ZipArchive(instream))
{
foreach(ZipArchiveEntry et in zip.Entries)
{
using(Stream stream = et.Open())
{
using(FileStream fsout = File.Create(et.Name))
{
stream.CopyTo(fsout);
}
}
}
}
}
使用GZipStream类压缩文件
GZIP(全称GNUzip)扩展名为.gz,是一种数据压缩格式,以GZipStream
类来封装GZip算法相关功能。
Console.WriteLine("请输入待压缩文件的路径:");
string inFilePath = Console.ReadLine();
string outFileName = "demo.gz";
if (File.Exists(outFileName))
File.Delete(outFileName);
using (FileStream fsIn = File.OpenRead(inFilePath))
using (FileStream fsOut = File.Create(outFileName))
{
using (GZipStream gz = new GZipStream(fsOut, CompressionMode.Compress))
{
fsIn.CopyTo(gz);
}
}
FileInfo info1 = new FileInfo(inFilePath);
FileInfo info2 = new FileInfo(outFileName);
Console.WriteLine($"压缩前,文件大小:{info1.Length}");
Console.WriteLine($"压缩后,文件大小:{info2.Length}");
Console.Read();
本文来自博客园,作者:一纸年华,转载请注明原文链接:https://www.cnblogs.com/nullcodeworld/p/18210636