当前位置: 代码网 > it编程>编程语言>C# > 基于C#实现压缩和解压文件及文件夹

基于C#实现压缩和解压文件及文件夹

2024年05月18日 C# 我要评论
c#压缩和解压文件及文件夹有以下几种方式:zipfile(.net 4.5 system.io.compression命名空间中新提供的压缩类)ziparchivesharpziplib和dotnet

c#压缩和解压文件及文件夹有以下几种方式:

zipfile(.net 4.5 system.io.compression命名空间中新提供的压缩类)

ziparchive

sharpziplib和dotnetzip 

使用第三方压缩软件

使用zipfile

引用.net 4.5程序集:system.io.compression 和 system.io.compression.filesystem.

    public class compressionhelper
    {
        /// <summary>
        /// 将指定目录压缩为zip文件
        /// </summary>
        /// <param name="folderpath">文件夹地址 d:/1/ </param>
        /// <param name="zippath">zip地址 d:/1.zip </param>
        public static void compressdirectoryzip(string folderpath, string zippath)
        {
            directoryinfo directoryinfo = new directoryinfo(zippath);
 
            if (directoryinfo.parent != null)
            {
                directoryinfo = directoryinfo.parent;
            }
 
            if (!directoryinfo.exists)
            {
                directoryinfo.create();
            }
 
            system.io.compression.zipfile.createfromdirectory(folderpath, zippath, compressionlevel.optimal, false);
        }
 
        /// <summary>
        /// 将指定文件压缩为zip文件
        /// </summary>
        /// <param name="filepath">文件地址 d:/1.txt </param>
        /// <param name="zippath">zip地址 d:/1.zip </param>
        public static void compressfilezip(string filepath, string zippath)
        {
 
            fileinfo fileinfo = new fileinfo(filepath);
            string dirpath = fileinfo.directoryname?.replace("\\", "/") + "/";
            string temppath = dirpath + guid.newguid() + "_temp/";
            if (!directory.exists(temppath))
            {
                directory.createdirectory(temppath);
            }
            fileinfo.copyto(temppath + fileinfo.name);
            compressdirectoryzip(temppath, zippath);
            directoryinfo directory = new directoryinfo(temppath);
            if (directory.exists)
            {
                //将文件夹属性设置为普通,如:只读文件夹设置为普通
                directory.attributes = fileattributes.normal;
 
                directory.delete(true);
            }
        }
 
 
        /// <summary>
        /// 解压zip文件到指定目录
        /// </summary>
        /// <param name="zippath">zip地址 d:/1.zip</param>
        /// <param name="folderpath">文件夹地址 d:/1/</param>
        public static void decompresszip(string zippath, string folderpath)
        {
            directoryinfo directoryinfo = new directoryinfo(folderpath);
 
            if (!directoryinfo.exists)
            {
                directoryinfo.create();
            }
 
            system.io.compression.zipfile.extracttodirectory(zippath, folderpath);
        }
 
    }

使用ziparchive

    public class ziparchivehelper
    {
        public static void zipfile(string sourcefilepath, string zipfilepath)
        {
            system.io.compression.zipfile.createfromdirectory(sourcefilepath, zipfilepath);
 
            // 创建并添加被压缩文件
            using (filestream zipfiletoopen = new filestream(sourcefilepath, filemode.create))
            {
                using (ziparchive archive = new ziparchive(zipfiletoopen, ziparchivemode.create))
                {
                    string filename = system.io.path.getfilename(zipfilepath);
                    ziparchiveentry readmeentry = archive.createentry(filename);
                    using (system.io.stream stream = readmeentry.open())
                    {
                        byte[] bytes = system.io.file.readallbytes(zipfilepath);
                        stream.write(bytes, 0, bytes.length);
                    }
                }
            }
        }
 
        /// <summary>
        /// 在压缩文件中添加文件
        /// </summary>
        /// <param name="sourcefilepath"></param>
        /// <param name="zipfilepath"></param>
        public static void addzipfile(string sourcefilepath, string zipfilepath)
        {
            using (filestream zipfiletoopen = new filestream(zipfilepath, filemode.create))
            {
                using (ziparchive archive = new ziparchive(zipfiletoopen, ziparchivemode.create))
                {
                    string filename = system.io.path.getfilename(sourcefilepath);
                    ziparchiveentry readmeentry = archive.createentry(filename);
                    using (system.io.stream stream = readmeentry.open())
                    {
                        byte[] bytes = system.io.file.readallbytes(sourcefilepath);
                        stream.write(bytes, 0, bytes.length);
                    }
                }
            }
 
        }
 
        /// <summary>
        /// 解压压缩文件
        /// </summary>
        /// <param name="zipfilepath"></param>
        /// <param name="unzipfilepath"></param>
        public static void uzipfile(string zipfilepath, string unzipfilepath)
        {
            using (filestream instream = file.openread(zipfilepath))
            {
                using (ziparchive zip = new ziparchive(instream))
                {
 
                    foreach (ziparchiveentry et in zip.entries)
                    {
                        using (stream stream = et.open())
                        {
                            using (filestream fsout = file.create(system.io.path.combine(unzipfilepath, et.name)))
                            {
                                stream.copyto(fsout);
                            }
                        }
                    }
                }
            }
        }
    }

使用sharpziplib

    public class sharpziplib
    {
        /// <summary>
        /// 压缩文件夹
        /// </summary>
        /// <param name="dirpath">文件夹路径</param>
        /// <param name="password">压缩包设置密码(注:可为空)</param>
        /// <param name="zipfilepath">压缩包路径+名称+后缀(注:可为空,默认同目录)</param>
        /// <returns></returns>
        public string zipfiles(string dirpath, string password, string zipfilepath)
        {
            if (zipfilepath == string.empty)
            {
                //压缩文件名为空时使用文件夹名+.zip
                zipfilepath = getzipfilepath(dirpath);
            }
            try
            {
                string[] filenames = directory.getfiles(dirpath);
                using (zipoutputstream s = new zipoutputstream(file.create(zipfilepath)))
                {
                    s.setlevel(9);
                    s.password = password;
                    byte[] buffer = new byte[4096];
                    foreach (string file in filenames)
                    {
                        zipentry entry = new zipentry(path.getfilename(file));
                        entry.datetime = datetime.now;
                        s.putnextentry(entry);
                        using (filestream fs = file.openread(file))
                        {
                            int sourcebytes;
                            do
                            {
                                sourcebytes = fs.read(buffer, 0, buffer.length);
                                s.write(buffer, 0, sourcebytes);
                            } while (sourcebytes > 0);
                        }
                    }
                    s.finish();
                    s.close();
                }
                return zipfilepath;
            }
            catch (exception ex)
            {
                return ex.tostring();
            }
        }
 
        /// <summary>
        /// 减压文件夹
        /// </summary>
        /// <param name="zipfilepath">压缩包地址+名称+后缀</param>
        /// <param name="password">密码(注:可为空)</param>
        /// <param name="unzippath">减压后保存的路径(注:可为空,默认同目录)</param>
        /// <returns></returns>
        public string unzips(string zipfilepath, string password, string unzippath)
        {
            try
            {
                if (unzippath == string.empty)
                {
                    //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
                    unzippath = getunzipfilepath(zipfilepath);
                }
                if (createpath(unzippath) && isexistfilepath(zipfilepath))
                {
                    string directoryname = path.getdirectoryname(unzippath);
                    {
                        using (zipinputstream zipinstream = new zipinputstream(file.openread(zipfilepath)))
                        {
                            zipinstream.password = password;
                            zipentry entry = zipinstream.getnextentry();
                            do
                            {
                                using (filestream filestreamout = file.create(directoryname + "\\" + entry.name))
                                {
                                    int size = 2048;
                                    byte[] buffer = new byte[size];
                                    do
                                    {
                                        size = zipinstream.read(buffer, 0, buffer.length);
                                        filestreamout.write(buffer, 0, size);
                                    } while (size > 0);
                                    filestreamout.close();
                                    filestreamout.dispose();
                                }
                            } while ((entry = zipinstream.getnextentry()) != null);
                            zipinstream.close();
                            zipinstream.dispose();
                            return unzippath;
                        }
                    }
                }
                return "请确认压缩包文件地址与解压后保存地址是否可以访问!";
            }
            catch (exception ex)
            {
                return ex.tostring();
            }
        }
 
        /// <summary>  
        /// 压缩文件  
        /// </summary>  
        /// <param name="dirfilepath">文件路径+名称+后缀</param>
        /// <param name="password">压缩包设置密码(注:可为空)</param>
        /// <param name="zipfilepath">压缩包路径+名称+后缀(注:可为空,默认同目录)</param>
        public string zipfile(string dirfilepath, string password, string zipfilepath)
        {
            try
            {
                if (isexistfilepath(dirfilepath))
                {
                    if (zipfilepath == string.empty)
                    {
                        zipfilepath = getzipfilepath(dirfilepath.replace(path.getextension(dirfilepath), ""));
                    }
                    string filename = path.getfilename(dirfilepath);
                    filestream streamtozip = new filestream(dirfilepath, filemode.open, fileaccess.read);
                    filestream zipfile = file.create(zipfilepath);
                    using (zipoutputstream zipstream = new zipoutputstream(zipfile))
                    {
                        zipentry zipentry = new zipentry(filename);
                        zipstream.putnextentry(zipentry);
                        zipstream.setlevel(9);
                        zipstream.password = password;
                        byte[] buffer = new byte[2048];
                        system.int32 size = streamtozip.read(buffer, 0, buffer.length);
                        zipstream.write(buffer, 0, size);
                        while (size < streamtozip.length)
                        {
                            int sizeread = streamtozip.read(buffer, 0, buffer.length);
                            zipstream.write(buffer, 0, sizeread);
                            size += sizeread;
                        }
                        zipstream.finish();
                        zipstream.close();
                        streamtozip.close();
                    }
                    return zipfilepath;
                }
                return "请确认压缩包文件地址与解压后保存地址是否可以访问!";
            }
            catch (exception ex)
            {
                return ex.tostring();
            }
        }
 
        /// <summary>
        /// 创建路径
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public bool createpath(string path)
        {
            try
            {
                if (!directory.exists(path))
                {
                    directory.createdirectory(path);
                    return true;
                }
                return true;
            }
            catch (exception)
            {
                return false;
            }
        }
 
        /// <summary>
        /// 文件是否存在
        /// </summary>
        /// <param name="filepath">路劲+名称+后缀</param>
        /// <returns></returns>
        public bool isexistfilepath(string filepath)
        {
            if (!file.exists(filepath))
            {
                return false;
            }
            return true;
        }
 
        /// <summary>
        /// 获取默认压缩路径+文件名+后缀【.zip】
        /// </summary>
        /// <param name="path">需要压缩的文件夹路径(注:不包含.后缀)</param>
        /// <returns>与压缩文件同一目录路径</returns>
        public string getzipfilepath(string path)
        {
            if (path.endswith("\\"))
            {
                path = path.substring(0, path.length - 1);
            }
            return path + ".zip";
        }
 
        /// <summary>
        ///  获取默认解压路径
        /// </summary>
        /// <param name="path">需要解压的压缩包文件地址</param>
        /// <returns>与解压文件同一目录路径</returns>
        public string getunzipfilepath(string path)
        {
            path = path.replace(path.getfilename(path), path.getfilenamewithoutextension(path));
            if (!path.endswith("/"))
            {
                path += "/";
            }
            return path;
        }
 
        /// <summary>
        /// 获取路径中所有文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        private hashtable getallfies(string path)
        {
            hashtable fileslist = new hashtable();
            directoryinfo filedire = new directoryinfo(path);
            if (filedire.exists)
            {
                this.getalldirfiles(filedire, fileslist);
                this.getalldirsfiles(filedire.getdirectories(), fileslist);
            }
            this.getalldirfiles(filedire, fileslist);
            this.getalldirsfiles(filedire.getdirectories(), fileslist);
            return fileslist;
        }
 
        /// <summary>  
        /// 获取一个文件夹下的所有文件夹里的文件  
        /// </summary>  
        /// <param name="dirs"></param>  
        /// <param name="fileslist"></param>  
        private void getalldirsfiles(directoryinfo[] dirs, hashtable fileslist)
        {
            foreach (directoryinfo dir in dirs)
            {
                foreach (fileinfo file in dir.getfiles("*.*"))
                {
                    fileslist.add(file.fullname, file.lastwritetime);
                }
                this.getalldirsfiles(dir.getdirectories(), fileslist);
            }
        }
 
        /// <summary>  
        /// 获取一个文件夹下的文件  
        /// </summary>  
        /// <param name="strdirname">目录名称</param>  
        /// <param name="fileslist">文件列表hasttable</param>  
        private void getalldirfiles(directoryinfo dir, hashtable fileslist)
        {
            foreach (fileinfo file in dir.getfiles("*.*"))
            {
                fileslist.add(file.fullname, file.lastwritetime);
            }
        }
    }

使用第三方压缩软件

    public  class winrarzip
    {
        public static bool zip(string strzippath, string strtxtpath, string password)
        {
            try
            {
                system.diagnostics.process process1 = new system.diagnostics.process();
                process1.startinfo.filename = "winrar.exe";
                process1.startinfo.createnowindow = true;
                process1.startinfo.arguments = " a -p" + password + " " + strzippath + " " + strtxtpath;
                //strtxtpath = "c://freezip//";
                //process1.startinfo.arguments = " x -p123456 " + strzippath + " " + strtxtpath;
                process1.start();
                if (process1.hasexited)
                {
                    return true;
                }
                return true;
            }
            catch (exception)
            {
                return false;
            }
 
        }
 
        public static bool uzip(string strzippath, string strtxtpath, string password)
        {
            try
            {
                system.diagnostics.process process1 = new system.diagnostics.process();
                process1.startinfo.filename = "winrar.exe";
                process1.startinfo.createnowindow = true;
                //process1.startinfo.arguments = " a -p123456 " + strzippath + " " + strtxtpath;
                //strtxtpath = "c://freezip//";
                process1.startinfo.arguments = " x -p" + password + " " + strzippath + " " + strtxtpath;
                process1.start();
                if (process1.hasexited)
                {
                    return true;
                }
                return true;
            }
            catch (exception)
            {
 
                return false;
            }
 
        }
    }

到此这篇关于基于c#实现压缩和解压文件及文件夹的文章就介绍到这了,更多相关c#压缩和解压文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com