[C#]用.NET框架实现ZIP单文件压缩

本文详细介绍了C# .NET环境下压缩文件的基本概念、实现细节及代码实例,包括隐藏文件、特定扩展名文件的压缩处理流程,以及文件的解压逻辑。通过一个基类和子类的实现方式展示了如何封装压缩与解压功能,适用于开发者在项目中高效处理文件压缩需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先来看实现:

namespace DSTDownloader
{
    class __Compress__
    {
        string dirpath=@".\temp\";

        protected void compressfile(FileInfo fi)
        {
            using (FileStream inFile = fi.OpenRead())
            {
                if ((File.GetAttributes(fi.FullName)&FileAttributes.Hidden)!=FileAttributes.Hidden&fi.Extension!=".dst")
                {
                    using (FileStream outFile = File.Create(fi.FullName + ".dst"))
                    {
                        using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
                        {
                            inFile.CopyTo(Compress);
                        }
                    }
                }
            }
        }

        protected bool decompressfile(FileInfo fi,string fileext)
        {
            try
            {
                using (FileStream inFile = fi.OpenRead())
                {
                    string curFile = fi.FullName;
                    string origName = curFile.Remove(curFile.Length - fi.Extension.Length);
                    using (FileStream outFile = File.Create(origName + fileext))
                    {
                        using (GZipStream Decompress = new GZipStream(inFile, CompressionMode.Decompress))
                        {
                            Decompress.CopyTo(outFile);
                        }
                    }
                }
                return true;
            }
            catch(Exception)
            {
                System.Windows.Forms.MessageBox.Show("读取更新包失败,请联系管理员!","错误");
                return false;
            }
        }
    }
    class MyCompress : __Compress__
    {
        //public void CompressFile(FileInfo FI)
        //{
        //    compressfile(FI);
        //}

        public bool Decompressfile(FileInfo FI,string filext)
        {
            return decompressfile(FI, filext);
        }
    }
}

有一个基类,__Compress__,所有压缩的算法都在里面,MyCompress类继承于__Compress__,提供了压缩的接口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值