C# 解压及压缩文件源代码

本文介绍了一个使用C#实现文件压缩与解压缩的方法,包括如何利用SharpZipLib库来完成Zip格式文件的压缩与解压缩操作。通过具体的代码示例展示了创建Zip文件及从Zip文件中提取文件的过程。

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

using System.IO;
using System.Windows.Forms;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
   public void unZip(string strSouceFile, string strDestFile)
        {
            if (!Directory.Exists(strDestFile))
                Directory.CreateDirectory(strDestFile);
            using (ZipInputStream zip = new ZipInputStream(File.OpenRead(strSouceFile)))
            {
                ZipEntry theEntry;
                string fileName;
                FileStream streamWriter;
                while ((theEntry = zip.GetNextEntry()) != null)
                {
                    fileName = Path.GetFileName(theEntry.Name);

                    if (fileName != String.Empty)
                    {
                        streamWriter = new FileStream(strDestFile + fileName, FileMode.Create, FileAccess.Write, FileShare.Read | FileShare.Write);

                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = zip.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);

                            }
                            else
                            {
                                break;
                            }
                        }
                        streamWriter.Close();
                    }
                }
                MessageBox.Show("解压文件成功!

","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); } } public void ZipFile(string strSouceFile, string strDestFile) { using (ZipOutputStream stream = new ZipOutputStream(File.Create(strDestFile))) { stream.SetLevel(5); byte[] buffer = new byte[0x1000]; ZipEntry entry = new ZipEntry(Path.GetFileName(strSouceFile)); entry.DateTime = DateTime.Now; stream.PutNextEntry(entry); using (FileStream stream2 = File.OpenRead(strSouceFile)) { int num; do { num = stream2.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, num); } while (num > 0); MessageBox.Show("压缩文件成功!

"); } stream.Finish(); stream.Close(); } }

须要引用的dll,下载下面页面的dll
http://download.youkuaiyun.com/detail/sky_cat/7236675
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值