• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#解压或压缩文件夹 - 韩显川

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

C#解压或压缩文件夹

最近要做一个项目涉及到C#中压缩与解压缩的问题的解决方法,大家分享。
这里主要解决文件夹包含文件夹的解压缩问题。
1)下载SharpZipLib.dll,在http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx中有最新免费版本,“Assemblies for .NET 1.1, .NET 2.0, .NET CF 1.0, .NET CF 2.0: Download [297 KB] ”点击Download可以下载,解压后里边有好多文件夹,因为不同的版本,我用的FW2.0。
2)引用SharpZipLib.dll,在项目中点击项目右键-->添加引用-->浏览,找到要添加的DLL-->确认


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;

/*
 * 
http://www.icsharpcode.net/OpenSource/SharpZipLib/ 下载ICSharpCode.SharpZipLib
* 解压缩
* 该程序压缩和解压配合才能使用
* 普通用 Winrar 压缩的文件该解压不能通过
*/
namespace ZipApplication
{

    
#region ZipClass

    
/// <summary>
    
/// 压缩类
    
/// </summary>
    public class ZipClass
    {

        
#region ZipFileDictory

        
/// <summary>
        
/// 递归压缩文件夹方法
        
/// </summary>
        
/// <param name="FolderToZip"></param>
        
/// <param name="s"></param>
        
/// <param name="ParentFolderName"></param>
        private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName)
        {
            
bool res = true;
            
string[] folders, filenames;
            ZipEntry entry 
= null;
            FileStream fs 
= null;
            Crc32 crc 
= new Crc32();
            
try
            {
                
//创建当前文件夹
                entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/"));  //加上 “/” 才会当成是文件夹创建
                s.PutNextEntry(entry);
                s.Flush();
                
//先压缩文件,再递归压缩文件夹 
                filenames = Directory.GetFiles(FolderToZip);
                
foreach (string file in filenames)
                {
                    
//打开压缩文件
                    fs = File.OpenRead(file);

                    
byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 
0, buffer.Length);
                    entry 
= new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file)));
                    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);
                }
            }
            
catch
            {
                res 
= false;
            }
            
finally
            {
                
if (fs != null)
                {
                    fs.Close();
                    fs 
= null;
                }
                
if (entry != null)
                    entry 
= null;
                GC.Collect();
                GC.Collect(
1);
            }
            folders 
= Directory.GetDirectories(FolderToZip);
            
foreach (string folder in folders)
            {
                
if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
                    
return false;
            }
            
return res;
        }

        
#endregion


        
#region ZipFileDictory

        
/// <summary>
        
/// 压缩目录
        
/// </summary>
        
/// <param name="FolderToZip">待压缩的文件夹,全路径格式</param>
        
/// <param name="ZipedFile">压缩后的文件名,全路径格式</param>
        
/// <returns></returns>
        private static bool ZipFileDictory(string FolderToZip, string ZipedFile, string Password)
        {
            
bool res;
            
if (!Directory.Exists(FolderToZip))
                
return false;
            ZipOutputStream s 
= new ZipOutputStream(File.Create(ZipedFile));
            s.SetLevel(
6);
            
if(!string.IsNullOrEmpty(Password.Trim()))
                s.Password 
= Password.Trim();
            res 
= ZipFileDictory(FolderToZip, s, "");
            s.Finish();
            s.Close();
            
return res;
        }

        
#endregion

        
#region ZipFile

        
/// <summary>
        
/// 压缩文件
        
/// </summary>
        
/// <param name="FileToZip">要进行压缩的文件名</param>
        
/// <param name="ZipedFile">压缩后生成的压缩文件名</param>
        
/// <returns></returns>
        private static bool ZipFile(string FileToZip, string ZipedFile, string Password)
        {
            
//如果文件没有找到,则报错
            if (!File.Exists(FileToZip))
                
throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!");
            
//FileStream fs = null;
            FileStream ZipFile = null;
            ZipOutputStream ZipStream 
= null;
            ZipEntry ZipEntry 
= null;
            
bool res = true;
            
try
            {
                ZipFile 
= File.OpenRead(FileToZip);
                
byte[] buffer = new byte[ZipFile.Length];
                ZipFile.Read(buffer, 
0, buffer.Length);
                ZipFile.Close();
                ZipFile 
= File.Create(ZipedFile);
                ZipStream 
= new ZipOutputStream(ZipFile);
                
if(!string.IsNullOrEmpty(Password.Trim()))
                    ZipStream.Password 
= Password.Trim();
                ZipEntry 
= new ZipEntry(Path.GetFileName(FileToZip));
                ZipStream.PutNextEntry(ZipEntry);
                ZipStream.SetLevel(
6);
                ZipStream.Write(buffer, 
0, buffer.Length);
            }
            
catch
            {
                res 
= false;
            }
            
finally
            {
                
if (ZipEntry != null)
                {
                    ZipEntry 
= null;
                }
                
if (ZipStream != null)
                {
                    ZipStream.Finish();
                    ZipStream.Close();
                }
                
if (ZipFile != null)
                {
                    ZipFile.Close();
                    ZipFile 
= null;
                }
                GC.Collect();
                GC.Collect(
1);
            }

            
return res;
        }

        
#endregion

        
#region Zip

        
/// <summary>
        
/// 压缩文件 和 文件夹
        
/// </summary>
        
/// <param name="FileToZip">待压缩的文件或文件夹,全路径格式</param>
        
/// <param name="ZipedFile">压缩后生成的压缩文件名,全路径格式</param>
        
/// <param name="Password">压缩密码</param>
        
/// <returns></returns>
        public static bool Zip(string FileToZip, string ZipedFile, string Password)
        {
            
if (Directory.Exists(FileToZip))
            {
                
return ZipFileDictory(FileToZip, ZipedFile, Password);
            }
            
else if (File.Exists(FileToZip))
            {
                
return ZipFile(FileToZip, ZipedFile, Password);
            }
            
else
            {
                
return false;
            }
        }

        
/// <summary>
        
/// 压缩文件 和 文件夹
        
/// </summary>
        
/// <param name="FileToZip">待压缩的文件或文件夹,全路径格式</param>
        
/// <param name="ZipedFile">压缩后生成的压缩文件名,全路径格式</param>
        
/// <returns></returns>
        public static bool Zip(string FileToZip, string ZipedFile)
        {
            
return Zip(FileToZip, ZipedFile, "");
        }

        
#endregion
    }

    
#endregion


    
#region UnZipClass

    
/// <summary>
    
///  解压类
    
/// </summary>
    public class UnZipClass
    {

        
#region UnZip

        
/// <summary>
        
/// 解压功能(解压压缩文件到指定目录)
        
/// </summary>
        
/// <param name="FileToUpZip">待解压的文件</param>
        
/// <param name="ZipedFolder">指定解压目标目录</param>
        
/// <param name="Password">指定解压密码</param>
        public static void UnZip(string FileToUpZip, string ZipedFolder, string Password)
        {
            
if (!File.Exists(FileToUpZip))
                
return;

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


            
using (ZipInputStream s = new ZipInputStream(File.OpenRead(FileToUpZip)))
            {

                
if (!string.IsNullOrEmpty(Password.Trim()))
                    s.Password 
= Password.Trim();

                ZipEntry theEntry;

                
int size = 2048;
                
long fszie;
                
int byteLenght;
                

                
while ((theEntry = s.GetNextEntry()) != null)
                {
                    
                    System.Windows.Forms.MessageBox.Show(s.Length.ToString());
                    
//Console.WriteLine(theEntry.Name);

                    
string directoryName = Path.GetDirectoryName(theEntry.Name);
                    
string fileName = Path.GetFileName(theEntry.Name);

                    
// create directory
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    
if (fileName != String.Empty)
                    {
                        fszie 
= theEntry.Size;
                        
using (FileStream streamWriter = File.Create(theEntry.Name))
                        {
                            
while (fszie > 0)
                            {
                                
if (fszie > (long)size)
                                    byteLenght 
= size;
                                
else
                                    byteLenght 
= Convert.ToInt32(fszie);
                                fszie 
= fszie - size;
                                
byte[] data = new byte[byteLenght];
                                s.Read(data, 
0, byteLenght);
                                streamWriter.Write(data, 
0, byteLenght);
                            }
                     &nbs

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#泛型与泛型约束发布时间:2022-07-10
下一篇:
[C#网络编程系列]专题五:TCP编程发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap