| C#文件或文件夹压缩和解压方法(通过ICSharpCode.SharpZipLib.dll)
					当前位置:点晴教程→知识管理交流
					
					→『 技术文档交流 』
					
				 
 我在网上收集一下文件的压缩和解压的方法,是通过ICSharpCode.SharpZipLib.dll 来实现的 一、介绍的目录 第一步:下载压缩和解压的 ICSharpCode.SharpZipLib.dll 支持库 第二步:创建一个压缩和解压的demo项目 第三步:查看压缩和解压的文件的结果 
 二、demo演示(包括源码和界面) 1、下载文件压缩和解压的支持库dll ,下载地址:附件:文件压缩和解压(SharpZipLib).zip 2、创建window创建项目 
 
 1) 添加引用(文件压缩和解压的dll) 
 
 2) 编写文件压缩和解压方法 选中项目,创建Model文件夹,添加连个类名,压缩类(ZipFloClass)和解压类(UnZipFloClass) 2.1)压缩类(ZipFloClass) using
ICSharpCode.SharpZipLib.Checksums; using
ICSharpCode.SharpZipLib.Zip; using
System; using
System.Collections.Generic; using
System.IO; using
System.Linq; using
System.Text; using
System.Threading.Tasks; 
 namespace ZipCompressTest.Model { ///     ///
压缩的方法 ///     public  class
ZipFloClass     {        
public void ZipFile(string
strFile, string strZip)        
{            
var len = strFile.Length;            
var strlen = strFile[len - 1];            
if (strFile[strFile.Length - 1]
!= Path.DirectorySeparatorChar)            
{                 strFile +=
Path.DirectorySeparatorChar;            
}            
ZipOutputStream outstream = new ZipOutputStream(File.Create(strZip));            
outstream.SetLevel(6);             zip(strFile, outstream, strFile);            
outstream.Finish();            
outstream.Close();        
} 
        
public void zip(string
strFile, ZipOutputStream outstream, string staticFile)        
{            
if (strFile[strFile.Length - 1]
!= Path.DirectorySeparatorChar)            
{                 strFile +=
Path.DirectorySeparatorChar;            
}            
Crc32 crc = new Crc32();            
//获取指定目录下所有文件和子目录文件名称            
string[] filenames =
Directory.GetFileSystemEntries(strFile);            
//遍历文件            
foreach (string file in
filenames)            
{                 if
(Directory.Exists(file))                 {                     zip(file, outstream,
staticFile);                 }                 //否则,直接压缩文件            
    else                 {                     //打开文件                     FileStream fs =
File.OpenRead(file);                     //定义缓存区对象                     byte[]
buffer = new byte[fs.Length];                     //通过字符流,读取文件                     fs.Read(buffer, 0,
buffer.Length);                     //得到目录下的文件(比如:D:\Debug1\test),test                     string
tempfile = file.Substring(staticFile.LastIndexOf("\\")
+ 1);                     ZipEntry entry = new
ZipEntry(tempfile);                     entry.DateTime = DateTime.Now;                     entry.Size = fs.Length;                     fs.Close();                     crc.Reset();                     crc.Update(buffer);                     entry.Crc = crc.Value;                     outstream.PutNextEntry(entry);                     //写文件                     outstream.Write(buffer, 0,
buffer.Length);                 }            
}        
}     } 
 } 
 2.2)解压类(UnZipFloClass) usingICSharpCode.SharpZipLib.Zip;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceZipCompressTest.Model{    ///     /// 解压方法    ///     publicclassUnZipFloClass    {        publicstringunZipFile(stringTargetFile, stringfileDir, refstringmsg)        {            stringrootFile = "";            msg = "";            try            {                //读取压缩文件(zip文件),准备解压缩                ZipInputStream inputstream = newZipInputStream(File.OpenRead(TargetFile.Trim()));                ZipEntry entry;                stringpath = fileDir;                //解压出来的文件保存路径                stringrootDir = "";                //根目录下的第一个子文件夹的名称                while((entry = inputstream.GetNextEntry()) != null)                {                    rootDir = Path.GetDirectoryName(entry.Name);                    //得到根目录下的第一级子文件夹的名称                    if(rootDir.IndexOf("\\") >= 0)                    {                        rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);                    }                    stringdir = Path.GetDirectoryName(entry.Name);                    //得到根目录下的第一级子文件夹下的子文件夹名称                    stringfileName = Path.GetFileName(entry.Name);                    //根目录下的文件名称                    if(dir != "")                    {                        //创建根目录下的子文件夹,不限制级别                        if(!Directory.Exists(fileDir + "\\"+ dir))                        {                            path = fileDir + "\\"+ dir;                            //在指定的路径创建文件夹                            Directory.CreateDirectory(path);                        }                    }                    elseif(dir == ""&& fileName != "")                    {                        //根目录下的文件                        path = fileDir;                        rootFile = fileName;                    }                    elseif(dir != ""&& fileName != "")                    {                        //根目录下的第一级子文件夹下的文件                        if(dir.IndexOf("\\") > 0)                        {                            //指定文件保存路径                            path = fileDir + "\\"+ dir;                        }                    }                    if(dir == rootDir)                    {                        //判断是不是需要保存在根目录下的文件                        path = fileDir + "\\"+ rootDir;                    }                    //以下为解压zip文件的基本步骤                    //基本思路:遍历压缩文件里的所有文件,创建一个相同的文件                    if(fileName != String.Empty)                    {                        FileStream fs = File.Create(path + "\\"+ fileName);                        intsize = 2048;                        byte[] data = newbyte[2048];                        while(true)                        {                            size = inputstream.Read(data, 0, data.Length);                            if(size > 0)                            {                                fs.Write(data, 0, size);                            }                            else                            {                                break;                            }                        }                        fs.Close();                    }                }                inputstream.Close();                msg = "解压成功!";                returnrootFile;            }            catch(Exception ex)            {                msg = "解压失败,原因:"+ ex.Message;                return"1;"+ ex.Message;            }        }    }}
 3)窗体页面的调用 3.1)窗体布局 
 
 3.2)对应的调用方法 usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;usingZipCompressTest.Model;namespaceZipCompressTest{    publicpartialclassForm1 : Form    {        publicForm1()        {            InitializeComponent();        }        ///         /// 压缩事件        ///         ///         ///         privatevoidbtnZipFlo_Click(objectsender, EventArgs e)        {            string[] strs = newstring[2];            //待压缩文件目录            strs[0] = "D:\\DeBug1\\";            //压缩后的目标文件            strs[1] = "D:\\Debug2\\FrpTest.zip";            ZipFloClass zc = newZipFloClass();            zc.ZipFile(strs[0], strs[1]);        }        ///         /// 解压事件        ///         ///         ///         privatevoidbtnUnZipFlo_Click(objectsender, EventArgs e)        {            string[] strs = newstring[2];            stringmsg = "";            //待解压的文件            strs[0] = "D:\\Debug2\\FrpTest.zip";            //解压后放置的目标文件            strs[1] = "D:\\Debug3\\";            UnZipFloClass uzc = newUnZipFloClass();            uzc.unZipFile(strs[0], strs[1], refmsg);            MessageBox.Show("信息:"+ msg);        }        ///         /// 批量压缩事件        ///         ///         ///         privatevoidbtnBatchZipFlo_Click(objectsender, EventArgs e)        {            stringpath1 = "D:\\DeBug1\\";   //待压缩的目录文件            stringpath2 = "D:\\Debug2\\";   //压缩后存放目录文件            //获取指定目录下所有文件和子文件名称(所有待压缩的文件)            string[] files = Directory.GetFileSystemEntries(path1);            ZipFloClass zc = newZipFloClass();            //遍历指定目录下文件路径            foreach(stringfile infiles)            {                //截取文件路径的文件名                varfilename = file.Substring(file.LastIndexOf("\\") + 1);                //调用压缩方法(参数1:待压缩的文件目录,参数2:压缩后的文件目录(包含后缀))                zc.ZipFile(path1 + filename, path2 + filename + ".zip");            }        }        ///         /// 批量解压事件        ///         ///         ///         privatevoidbtnBatchUnZipFlo_Click(objectsender, EventArgs e)        {            stringmsg = "";            stringpath2 = "D:\\Debug2\\";            stringpath3 = "D:\\Debug3\\";            //获取指定目录下所有文件和子文件名称(所有待解压的压缩文件)            string[] files = Directory.GetFileSystemEntries(path2);            UnZipFloClass uzc = newUnZipFloClass();            //遍历所有压缩文件路径            foreach(stringfile infiles)            {                //获取压缩包名称(包括后缀名)                varfilename  = file.Substring(file.LastIndexOf("\\") + 1);                //得到压缩包名称(没有后缀)                filename = filename.Substring(0, filename.LastIndexOf("."));                //判断解压的路径是否存在                if(!Directory.Exists(path3 + filename))                {                    //没有,则创建这个路径                    Directory.CreateDirectory(path3 + filename);                }                //调用解压方法(参数1:待解压的压缩文件路径(带后缀名),参数2:解压后存放的文件路径,参数3:返工是否解压成功)                uzc.unZipFile(file, path3 + filename, refmsg);            }            MessageBox.Show("批量解压成功");        }    }}
 3.3) 物理路径创建3个文件,Dubug1,Dubug2,Dubug3 
 
 3、测试结果界面 3.1)demo 程序的界面 
 
 3.2)批量压缩/解压文件视图 
 3.3)批量压缩的结果视图 
 3.4) 批量解压的结果视图 三、demo源码下载 下载demo附件:ZipCompressTest.zip 参考资料来源:http://www.cnblogs.com/zfanlong1314/p/4202695.html#commentform 该文章在 2021/3/8 10:42:12 编辑过 
 | 关键字查询 相关文章 正在查询... | ||||||