通过ICSharpCode.SharpZipLib.dll压缩和解压ZIP文件

本文介绍了一种使用ICSharpCode.SharpZipLib.dll类库实现ZIP文件压缩与解压的方法。通过具体代码示例展示了如何在C#中实现ZIP文件的压缩和解压过程。

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

在文件下载的过程中,为了增加下载的速度和减小网络流量,在下载之前需要对文件进行压缩操作,下载结束后,还要将下载的文件进行解压操作,大家都知道,现在压缩技术比较好的是RAR技术,但RAR编码规则是非公开的,所以我采用了ZIP技术对文件进行处理,引用了ICSharpCode.SharpZipLib.dll类库。

解压文件

         /// <summary>
        /// 解压ZIP文件
        /// </summary>
        /// <param name="filePath">Zip文件文件名,包含目录</param>
        private void Unzip(string filePath)
        {
           
            ZipInputStream s = new ZipInputStream(File.OpenRead(filePath));

            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
               
                string fullname = @"/Program Files/" + theEntry.Name;

                string directoryName = Path.GetDirectoryName(fullname);
                string fileName = Path.GetFileName(fullname);

                if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);

                if (fileName != String.Empty)
                {
                    FileStream streamWriter = File.Create(fullname);

                    int size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);

                        if (size > 0) streamWriter.Write(data, 0, size);
                        else break;
                    }
                    streamWriter.Close();
                }
            }
            s.Close();
        }

压缩文件

private void Zip()
{

string target = @"C:/TEST";

string[] filenames = GetFileList(target);
               
Crc32 crc = new Crc32();


ZipOutputStream s = new ZipOutputStream(File.Create(@"C:/test.zip"));
               
s.SetLevel(6); // (0~9)
               
foreach (string file in filenames)
{
   FileStream fs = File.OpenRead(file);
                       
   byte[] buffer = new byte[fs.Length];
   fs.Read(buffer, 0, buffer.Length);
  

   ZipEntry entry = new ZipEntry(file.Replace(target,""));
                       
   entry.DateTime = DateTime.Now;
                       
   entry.Size = fs.Length;
   fs.Close();
                       
   crc.Reset();
   crc.Update(buffer);
                       
   entry.Crc = crc.Value;
                        
   s.PutNextEntry(entry); //                         
   s.Write(buffer, 0, buffer.Length);                       
}
               
s.Finish();
s.Close();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值