当前位置: 代码网 > it编程>编程语言>Asp.net > C#使用SevenZipSharp实现压缩文件和目录

C#使用SevenZipSharp实现压缩文件和目录

2025年01月09日 Asp.net 我要评论
c#使用sevenzipsharp的操作封装了一个类,方便使用sevenzipsharp,支持加入进度显示事件。双重加密压缩工具范例:using sevenzip;using system;using

c#使用sevenzipsharp的操作

封装了一个类,方便使用sevenzipsharp,支持加入进度显示事件。

双重加密压缩工具范例:

using sevenzip;
using system;
using system.collections.generic;
using system.io;
using system.linq;
using system.text;
using system.threading.tasks;
 
namespace processitems
{
    class sevenzipsharpuser
    {
        // 假设这是某个类中的一个事件定义
        public  event eventhandler<progresseventargs> progressupdated = null;
 
        public  static bool setsetlibrarypath()
        {
            //设置库路径
            string currentdirectory = appdomain.currentdomain.basedirectory;
            string dllpath = getappropriate7zdllpath(currentdirectory);
 
            if (!file.exists(dllpath))
            {
                return false;
            }
 
            sevenzipsharpuser.setsetlibrarypath(dllpath);
 
            return true;
        }
 
        public static void setsetlibrarypath(string s7zdllpath)
        {
            sevenzipbase.setlibrarypath(s7zdllpath);
        }
 
        public  bool compressitem(string inputitem, string outputfile, string password = null)
        {
            string directory = path.getdirectoryname(outputfile);
            if (!directory.exists(directory))
            {
                directory.createdirectory(directory);
            }
 
            if (directory.exists(inputitem))
            {
                return compressdir(inputitem, outputfile, password);
            }
            else if (file.exists(inputitem))
            {
                return compressfile(inputitem, outputfile, password);
            }
 
            return false;
        }
 
        public  bool doublecompressitem(string inputitem, string outputfile, string password1 = null, string password2 = null)
        {
            string directory = path.getdirectoryname(outputfile);
            string filenamewithoutextension = path.getfilenamewithoutextension(outputfile);
 
            string sfirstdstpath = path.combine(directory, $"{filenamewithoutextension}{".7zx"}");
 
            compressitem(inputitem, sfirstdstpath, password1);
            compressitem(sfirstdstpath, outputfile, password2);
 
            file.delete(sfirstdstpath);
 
            return false;
        }
 
        public  string getuniquefilepath(string filepath)
        {
            string directory = path.getdirectoryname(filepath);
            string filenamewithoutextension = path.getfilenamewithoutextension(filepath);
            string extension = path.getextension(filepath);
 
            int counter = 1;
            string newfilepath = filepath;
 
            while (file.exists(newfilepath))
            {
                newfilepath = path.combine(directory, $"{filenamewithoutextension}{counter}{extension}");
                counter++;
            }
 
            return newfilepath;
        }
 
        public  bool compressfile(string inputfile, string outputfile, string password = null)
        {
            try
            {
                // 检查输入文件是否存在
                if (!file.exists(inputfile))
                {
                    throw new filenotfoundexception("输入文件不存在。", inputfile);
                }
 
                // 创建 sevenzipcompressor 实例
                var compressor = new sevenzipcompressor();
                // 设置压缩级别和档案格式
                compressor.compressionlevel = compressionlevel.normal;
                compressor.archiveformat = outarchiveformat.sevenzip;
 
                // 订阅进度更新事件
                if (progressupdated != null)
                {
                    compressor.compressing += progressupdated;
                }
 
                // 压缩文件
                compressor.compressfilesencrypted(outputfile, password, inputfile);
 
                if (progressupdated != null)
                {
                    compressor.compressing -= progressupdated;
                }
 
                // 压缩成功后返回 true
                return true;
            }
            catch (exception ex)
            {
                // 在发生异常时记录日志、抛出异常或返回 false
                // 这里简单地返回 false,但你可以根据需要更改此行为
                console.writeline($"压缩文件时发生错误: {ex.message}");
                return false;
            }
            finally
            {
 
            }
        }
 
        public  bool compressdir(string stinputdir, string stoutputfile, string stpwd)
        {
            try
            {
                // 检查输入文件是否存在
                if (!directory.exists(stinputdir))
                {
                    throw new filenotfoundexception("输入目录不存在。", stinputdir);
                }
 
                // 创建 sevenzipcompressor 实例
                var compressor = new sevenzipcompressor();
                // 设置压缩级别和档案格式
                compressor.compressionlevel = compressionlevel.normal;
                compressor.archiveformat = outarchiveformat.sevenzip;
 
                // 订阅进度更新事件
                if (progressupdated != null)
                {
                    compressor.compressing += progressupdated;
                }
 
                // 压缩文件
                compressor.compressdirectory(stinputdir, stoutputfile, stpwd);
 
                if (progressupdated != null)
                {
                    compressor.compressing -= progressupdated;
                }
 
                // 压缩成功后返回 true
                return true;
            }
            catch (exception ex)
            {
                // 在发生异常时记录日志、抛出异常或返回 false
                // 这里简单地返回 false,但你可以根据需要更改此行为
                console.writeline($"压缩文件时发生错误: {ex.message}");
                return false;
            }
            finally
            {
 
            }
        }
 
        private static string getappropriate7zdllpath(string basepath)
        {
            string dllname = "7z.dll";
            string dllpath = path.combine(basepath, dllname);
 
            // check if the system is 64-bit or 32-bit
            if (environment.is64bitoperatingsystem)
            {
                // if the system is 64-bit, check for a specific 64-bit version of the dll
                string dll64path = path.combine(basepath, "7z.dll"); // example name for 64-bit version
                if (file.exists(dll64path))
                {
                    return dll64path;
                }
                // if the specific 64-bit version is not found, fall back to the generic name
            }
            else
            {
                // if the system is 32-bit, check for a specific 32-bit version of the dll
                string dll32path = path.combine(basepath, "7-zip32.dll"); // example name for 32-bit version
                if (file.exists(dll32path))
                {
                    return dll32path;
                }
                // if the specific 32-bit version is not found, fall back to the generic name
            }
 
            // if neither specific version is found, return the generic dll name (which might be a universal version or an error)
            return dllpath;
        }
    }
}

使用方法:

            //设置库
            if (!sevenzipsharpuser.setsetlibrarypath())
            {
                messagebox.show("7z.dll库引用失败!", "错误!", messageboxbuttons.ok, messageboxicon.error);
            }
 
            //这里是处理任务逻辑开始========start===========
            if (iteminfo.bdoublecompress)
            {
                szu.doublecompressitem(iteminfo.sitempath, iteminfo.sdstpath, iteminfo.spassword1, iteminfo.spassword2);
            }
            else
            {
                szu.compressitem(iteminfo.sitempath, iteminfo.sdstpath, iteminfo.spassword1);
            }
 
            //这里是处理任务逻辑结束========end=============

拓展:c#使用sevenzipsharp压缩解压文件

首先程序需要用到三个dll文件,分别是:sevenzipsharp.dll、7z.dll、7z64.dll,其中sevenzipsharp.dll需要程序进行引用,而其他两个文件给代码使用,其中7z.dll是32位,7z64.dll是64位的。(此处需要注意,这里的32位与64位指的是程序,而不是操作系统,即指的是vs中右键项目属性里的目标平台,可由system.intptr.size判断,4为32位,8为64位,当时因为这里的歧义踩过坑)

解压

伪代码:

	if(intptr.size == 4)    //32位操作系统
	{
     	 sevenzipcompressor.setlibrarypath(appdomain.currentdomain.basedirectory + @"\7z.dll"); //路径指向dll文件,此处dll放在与程序相同目录,以下相同。
     	 
	}
	else    //64位操作系统
	{
    	sevenzipcompressor.setlibrarypath(appdomain.currentdomain.basedirectory + @"\7z64.dll");
	}
	using (var tmp = new sevenzipextractor(“压缩文件全名称”))    //这里的全名称包含路径
    {
         tmp.extractarchive(“解压到的路径”);
    }

压缩

伪代码:

	if(intptr.size == 4)    //32位操作系统
	{
     	 sevenzipcompressor.setlibrarypath(appdomain.currentdomain.basedirectory + @"\7z.dll");
	}
	else    //64位操作系统
	{
    	sevenzipcompressor.setlibrarypath(appdomain.currentdomain.basedirectory + @"\7z64.dll");
	}
	var compressor = new sevenzipcompressor();
	//压缩文件夹:
	compressor.compressdirectory(目录名,压缩文件名称);//此处有多个重载,不一一列出。

	//压缩文件:
	var ziptool = new sevenzipcompressor();
	ziptool.archiveformat = outarchiveformat.zip;   //压缩文件类型
    string[] filenames = {“文件全路径”,“文件全路径” }; //需要添加到压缩文件的文件的全路径数组。
    ziptool.compressfiles(“压缩文件名称”, filenames); //传递压缩文件名称,及文件全路径数组。

以上就是c#使用sevenzipsharp实现压缩文件和目录的详细内容,更多关于c# sevenzipsharp压缩的资料请关注代码网其它相关文章!

(0)

相关文章:

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

发表评论

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