如前所述,流的一个特性是可以将它们链接起来。为了压缩流,只需要创建 DeflateStream,并给构造函数传递另一个流(在这个例子中,是写入文件的outputStream),使用 CompressionMode. Compress 表示压缩。使用 Write方法或其他功能写入这个流,如以下代码片段所示的 CopyTo()方法,就是文件压缩所需的所有操作:
public static void Compressfile(string fileName, string compressedFileName)
{using (FileStream inputStream = File.OpenRead(fileName)){FileStream outputStream = File.OpenWrite(compressedFileName); using (var compressStream =new DeflateStream(outputStream, CompressionMode.Compress)) {inputStream.CopyTo(compressStream);}}
}
为了再次把通过 DeflateStream 压缩的文件解压缩,下面的代码片段使用 FileStream打开文件,并创建 DeflateStream 对象,把CompressionMode.Decompress 传入文件流,表示解压缩。Stream.CopyTo 方法把解压缩的流复制到MemoryStream 中。然后,这个代码片段利用 StreamReader读取 MemoryStream 中的数据,把输出写到控制台。StreamReader 配置为打开所分配的 MemoryStream(使用leaveOpen参数),所以 MemoryStream 在关闭读取器后也可以使用:
public static void DecompressFile(string fileName)
{FileStream inputStream = File.OpenRead(fileName);using (MemoryStream outputStream = new MemoryStream())using (var compressStream = new DeflateStream(inputStream,CompressionMode.Decompress)){compressStream.CopyTo(outputStream);outputStream.Seek(0, SeekOrigin.Begin);using (var reader = new StreamReader(outputStream, Encoding.UTF8,detectEncodingFromByteOrderMarks: true, bufferSize: 4096, leaveOpen: true)){string result = reader.ReadToEnd(); Console.WriteLine(result);}// you could use the outputStream after the StreamReader is closed}
}
使用 BrotliStream,通过 Brotli 进行压缩像使用 deflate 一样。只需要添加NuGet包 System.IO.CompressionBrotli,并实例化 BrotliStream类:
public static void CompressFileWithBrotli(string fileName, string compressedfileName)
{using (FileStream inputStream = File.OpenRead(fileName)){FileStream outputStream = File.OpenWrite(compressedFileName); using (var compressStream =new BrotliStream(outputStream,CompressionMode.Compress)){inputStream.CopyTo(compressStream);}}
}
使用 BrotliStream 进行相应的解压工作:
public static void DecompressFileWithBrotli(string fileName)
{Filestream inputStream = File.OpenRead(fileName);using (MemoryStream outputStream = new MemoryStream()) using (var compresstStream = new BrotliStream(inputStream, CompressionMode.Decompress)){compressStream.CopyTo(outputStream);outputStream.Seek(0, SeekOrigin.Begin);using (var reader = new StreamReader(outputStream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, buffersize: 4096, leaveOpen: true)){string result = reader.ReadToEnd(); Console.WriteLine(result);}}
}
微信公众号
DotNet讲堂