using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO.Compression; using System.IO; namespace gzipfile { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //文件流 FileStream reader; reader = File.Open("D:\\ddd.txt", FileMode.Open); FileStream writer; writer = File.Create("D:\\ddd.gz"); //压缩相关的流 MemoryStream ms = new MemoryStream(); GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress, true); //往压缩流中写数据 byte[] sourceBuffer = new byte[reader.Length]; reader.Read(sourceBuffer, 0, sourceBuffer.Length); zipStream.Write(sourceBuffer, 0, sourceBuffer.Length); //一定要在内存流读取之前关闭压缩流 zipStream.Close(); zipStream.Dispose(); //从内存流中读数据 ms.Position = 0; //注意,不要遗漏此句 byte[] destBuffer = new byte[ms.Length]; //ms.Read(destBuffer, 0, destBuffer.Length); byte[] header = new byte [10]; ms.Read(header, 0, 10); header[3] = 8; //表示包含文件名信息 byte[] fielContent = new byte[ms.Length -10] ; ms.Read(fielContent, 0, fielContent.Length); string strfilename = "widebright的文件.txt"; //指定初始文件名 //byte [] filename=System.Text.Encoding.Convert(System.Text.Encoding.Default, // // System.Text.Encoding.GetEncoding("ISO-8859-1"), // System.Text.Encoding.Default, // System.Text.Encoding.Default.GetBytes(strfilename)); byte[] filename = System.Text.Encoding.Default.GetBytes(strfilename); writer.Write(header, 0, header.Length); writer.Write(filename, 0, filename.Length); writer.WriteByte(0); //文件名以0 字节结束 writer.Write(fielContent, 0, fielContent.Length); //关闭并释放内存流 ms.Close(); ms.Dispose(); //关闭并释放文件流 writer.Close(); writer.Dispose(); reader.Close(); reader.Dispose(); } } }
Net压缩文件流
最新推荐文章于 2022-07-15 17:12:14 发布