C#使用System.IO.Compression.GZipStream压缩和解压缩文件

82 篇文章 3 订阅

新建类GZipStreamUtil,源程序如下:

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

namespace SiemensPlcDemo
{
    /// <summary>
    /// 压缩与解压缩操作
    /// </summary>
    public class GZipStreamUtil
    {
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="srcFileName">源文件名</param>
        /// <param name="zipFileName">目标文件:压缩后的zip文件</param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public static bool CompressFile(string srcFileName, string zipFileName, out string exception)
        {
            exception = string.Empty;
            if (!File.Exists(srcFileName))
            {
                exception = $"初始文件不存在:【{srcFileName}】";
                return false;
            }
            try
            {                
                string directoryName = Path.GetDirectoryName(zipFileName);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                //读取文件到字节中
                byte[] buffer = ReadFileToBuffer(srcFileName);
                byte[] bufferWrite = CompressBytes(buffer);
                WriteFileFromBuffer(zipFileName, bufferWrite);
                return true;
            }
            catch (Exception ex) 
            {
                exception = $"压缩文件时出现异常:【{ex.Message}】";
                return false;
            }
        }

        /// <summary>
        /// 解压缩文件
        /// </summary>
        /// <param name="zipFileName">要解压的zip文件</param>
        /// <param name="srcFileName">初始源文件名</param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public static bool DecompressFile(string zipFileName, string srcFileName, out string exception)
        {
            exception = string.Empty;
            if (!File.Exists(zipFileName))
            {
                exception = $"压缩文件不存在:【{zipFileName}】";
                return false;
            }
            try
            {
                string directoryName = Path.GetDirectoryName(srcFileName);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                //读取文件到字节中
                byte[] buffer = ReadFileToBuffer(zipFileName);
                byte[] bufferWrite = Decompress(buffer);
                WriteFileFromBuffer(srcFileName, bufferWrite);
                return true;
            }
            catch (Exception ex)
            {
                exception = $"压缩文件时出现异常:【{ex.Message}】";
                return false;
            }
        }

        /// <summary>
        /// 将文件内容转化为字节流
        /// </summary>
        /// <param name="srcFileName"></param>
        /// <returns></returns>
        private static byte[] ReadFileToBuffer(string srcFileName) 
        {
            int fileSize = (int)new FileInfo(srcFileName).Length;
            byte[] buffer = new byte[fileSize];
            using (FileStream fileStream = new FileStream(srcFileName, FileMode.Open, FileAccess.Read))
            {
                using (BinaryReader binaryReader = new BinaryReader(fileStream))
                {
                    // 把文件指针重新定位到文件的开始
                    binaryReader.BaseStream.Seek(0, SeekOrigin.Begin);
                    //读取所有数据
                    buffer = binaryReader.ReadBytes(fileSize);
                    binaryReader.Close();
                }
                fileStream.Close();
            }
            return buffer;
        }

        /// <summary>
        /// 从指定的字节流写入文件
        /// </summary>
        /// <param name="destFileName">目标文件名</param>
        /// <param name="bufferWrite">要写入的字节流</param>
        private static void WriteFileFromBuffer(string destFileName, byte[] bufferWrite) 
        {
            //写入文件
            using (FileStream fileStream = new FileStream(destFileName, FileMode.Create, FileAccess.ReadWrite))
            {
                //以二进制方式写文件 
                //创建一个二进制数据流写入器,和打开的文件关联
                using (BinaryWriter binaryWriter = new BinaryWriter(fileStream))
                {
                    binaryWriter.Write(bufferWrite);
                    binaryWriter.Flush();
                    binaryWriter.Close();
                }
                fileStream.Close();
            }
        }

        /// <summary>
        /// 压缩字节数据
        /// 1.创建压缩的数据流 
        /// 2.设定compressStream为存放被压缩的文件流,并设定为压缩模式
        /// 3.将需要压缩的字节写到被压缩的文件流
        /// </summary>
        /// <param name="bytes">等待被压缩的数据</param>
        /// <returns>压缩之后的字节数据</returns>
        public static byte[] CompressBytes(byte[] bytes)
        {
            if (bytes == null) 
                throw new ArgumentNullException("初始被压缩的字节数据流不能为null");
            using (MemoryStream compressStream = new MemoryStream())
            {
                using (GZipStream zipStream = new GZipStream(compressStream, CompressionMode.Compress))
                    zipStream.Write(bytes, 0, bytes.Length);
                return compressStream.ToArray();
            }
        }

        /// <summary>
        /// 解压压缩后的数据
        /// 1.创建被压缩的数据流
        /// 2.创建zipStream对象,并传入解压的文件流
        /// 3.创建目标流
        /// 4.zipStream拷贝到目标流
        /// 5.返回目标流输出字节
        /// </summary>
        /// <param name="bytes">被压缩后的数据</param>
        /// <returns>压缩前的原始字节数据</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static byte[] Decompress(byte[] bytes)
        {
            if (bytes == null) 
                throw new ArgumentNullException("初始解压缩的字节数据流不能为null");
            using (MemoryStream compressStream = new MemoryStream(bytes))
            {
                using (GZipStream zipStream = new GZipStream(compressStream, CompressionMode.Decompress))
                {
                    using (MemoryStream resultStream = new MemoryStream())
                    {
                        int readLength = 1024;
                        byte[] buf = new byte[readLength];
                        int len = 0;
                        while ((len = zipStream.Read(buf, 0, readLength)) > 0)
                        {
                            resultStream.Write(buf, 0, len);
                        }
                        return resultStream.ToArray();
                    }
                }
            }
        }
    }
}

测试程序如下(windows窗体程序):

string srcFile = @"E:\scratch\制作一个少儿编程程序.docx";
            string zipFile = @"E:\scratch\制作一个少儿编程程序.zip";
            string srcFileBak = @"E:\scratch\制作一个少儿编程程序Bak.docx";
            string exception;
            bool result = GZipStreamUtil.CompressFile(srcFile, zipFile, out exception);
            MessageBox.Show($"压缩文件的结果:【{result}】,初始文件【{srcFile}】\n目标文件【{zipFile}】\n异常信息【{exception}】", "提示");
            result = GZipStreamUtil.DecompressFile(zipFile, srcFileBak, out exception);
            MessageBox.Show($"解压缩文件的结果:【{result}】,压缩文件【{srcFile}】\n目标源文件【{srcFileBak}】\n异常信息【{exception}】", "提示");

测试运行结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

斯内科

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值