C# GZipStream压缩与解压缩(针对文件)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace _压缩
{
    class Program
    {
        static void Main(string[] args)
        {
            //压缩
            //创建读取流
            using (FileStream fs = new FileStream("123.txt", FileMode.Open, FileAccess.Read))
            {
                //创建写入流
                using (FileStream save = new FileStream("456.zip", FileMode.Create, FileAccess.Write))
                {
                    //创建包含写入流的压缩流
                    using (GZipStream gs = new GZipStream(save, CompressionMode.Compress))
                    {
                        //创建byte[]数组中转数据
                        byte[] b = new byte[1024 * 1024];
                        int count = 0;
                        //循环将读取流中数据写入到byte[]数组中
                        while ((count = fs.Read(b, 0, b.Length)) > 0)
                        {
                            //将byte[]数组中数据写入到压缩流
                            gs.Write(b, 0, b.Length);
                        }
                    }
                }
            }
            //
            Console.WriteLine("压缩完毕!\n>");
            //解压
            //创建压缩文件读取流
            using (FileStream fs = new FileStream("456.zip", FileMode.Open, FileAccess.Read))
            {
                //目录文件写入流
                using (FileStream save = new FileStream("789.txt", FileMode.Create, FileAccess.Write))
                {
                    //创建包含压缩文件流的GZipStream流
                    using (GZipStream zipStream = new GZipStream(fs, CompressionMode.Decompress, true))
                    {
                        //创建byte[]数组中转数据
                        byte[] buf = new byte[1024];
                        int len;
                        //循环将解压流中数据写入到byte[]数组中
                        while ((len = zipStream.Read(buf, 0, buf.Length)) > 0)
                        {
                            //向目标文件流写入byte[]中转数组
                            save.Write(buf, 0, len);
                        }
                    }
                }
            }
            Console.WriteLine("解压完毕");
            Console.ReadKey();
        }
    }
}

你可能感兴趣的:(C#)