欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#使用SevenZipSharp實(shí)現(xiàn)壓縮文件和目錄

 更新時(shí)間:2025年01月08日 11:39:26   作者:秋月的私語(yǔ)  
SevenZipSharp壓縮/解壓(.7z?.zip)”是指使用SevenZipSharp庫(kù)進(jìn)行7z和zip格式的文件壓縮與解壓縮操作,SevenZipSharp是C#語(yǔ)言封裝的7-Zip?API,它使得在.NET環(huán)境中調(diào)用7-Zip的功能變得簡(jiǎn)單易行,本文給大家介紹了C#使用SevenZipSharp實(shí)現(xiàn)壓縮文件和目錄

C#使用SevenZipSharp的操作

封裝了一個(gè)類,方便使用SevenZipSharp,支持加入進(jìn)度顯示事件。

雙重加密壓縮工具范例:

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
    {
        // 假設(shè)這是某個(gè)類中的一個(gè)事件定義
        public  event EventHandler<ProgressEventArgs> ProgressUpdated = null;
 
        public  static bool SetSetLibraryPath()
        {
            //設(shè)置庫(kù)路徑
            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);
                }
 
                // 創(chuàng)建 SevenZipCompressor 實(shí)例
                var compressor = new SevenZipCompressor();
                // 設(shè)置壓縮級(jí)別和檔案格式
                compressor.CompressionLevel = CompressionLevel.Normal;
                compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
 
                // 訂閱進(jìn)度更新事件
                if (ProgressUpdated != null)
                {
                    compressor.Compressing += ProgressUpdated;
                }
 
                // 壓縮文件
                compressor.CompressFilesEncrypted(outputFile, password, inputFile);
 
                if (ProgressUpdated != null)
                {
                    compressor.Compressing -= ProgressUpdated;
                }
 
                // 壓縮成功后返回 true
                return true;
            }
            catch (Exception ex)
            {
                // 在發(fā)生異常時(shí)記錄日志、拋出異?;蚍祷?false
                // 這里簡(jiǎn)單地返回 false,但你可以根據(jù)需要更改此行為
                Console.WriteLine($"壓縮文件時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
                return false;
            }
            finally
            {
 
            }
        }
 
        public  bool CompressDir(string stInputDir, string stOutputFile, string stPwd)
        {
            try
            {
                // 檢查輸入文件是否存在
                if (!Directory.Exists(stInputDir))
                {
                    throw new FileNotFoundException("輸入目錄不存在。", stInputDir);
                }
 
                // 創(chuàng)建 SevenZipCompressor 實(shí)例
                var compressor = new SevenZipCompressor();
                // 設(shè)置壓縮級(jí)別和檔案格式
                compressor.CompressionLevel = CompressionLevel.Normal;
                compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
 
                // 訂閱進(jìn)度更新事件
                if (ProgressUpdated != null)
                {
                    compressor.Compressing += ProgressUpdated;
                }
 
                // 壓縮文件
                compressor.CompressDirectory(stInputDir, stOutputFile, stPwd);
 
                if (ProgressUpdated != null)
                {
                    compressor.Compressing -= ProgressUpdated;
                }
 
                // 壓縮成功后返回 true
                return true;
            }
            catch (Exception ex)
            {
                // 在發(fā)生異常時(shí)記錄日志、拋出異常或返回 false
                // 這里簡(jiǎn)單地返回 false,但你可以根據(jù)需要更改此行為
                Console.WriteLine($"壓縮文件時(shí)發(fā)生錯(cuò)誤: {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;
        }
    }
}

使用方法:

            //設(shè)置庫(kù)
            if (!SevenZipSharpUser.SetSetLibraryPath())
            {
                MessageBox.Show("7z.dll庫(kù)引用失敗!", "錯(cuò)誤!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
 
            //這里是處理任務(wù)邏輯開始========start===========
            if (itemInfo.bDoubleCompress)
            {
                szu.DoubleCompressItem(itemInfo.sItemPath, itemInfo.sDstPath, itemInfo.sPassword1, itemInfo.sPassword2);
            }
            else
            {
                szu.CompressItem(itemInfo.sItemPath, itemInfo.sDstPath, itemInfo.sPassword1);
            }
 
            //這里是處理任務(wù)邏輯結(jié)束========end=============

拓展:C#使用SevenZipSharp壓縮解壓文件

首先程序需要用到三個(gè)DLL文件,分別是:SevenZipSharp.dll、7z.dll、7z64.dll,其中SevenZipSharp.dll需要程序進(jìn)行引用,而其他兩個(gè)文件給代碼使用,其中7z.dll是32位,7z64.dll是64位的。(此處需要注意,這里的32位與64位指的是程序,而不是操作系統(tǒng),即指的是VS中右鍵項(xiàng)目屬性里的目標(biāo)平臺(tái),可由System.IntPtr.Size判斷,4為32位,8為64位,當(dāng)時(shí)因?yàn)檫@里的歧義踩過坑)

解壓

偽代碼:

	if(IntPtr.Size == 4)    //32位操作系統(tǒng)
	{
     	 SevenZipCompressor.SetLibraryPath(AppDomain.CurrentDomain.BaseDirectory + @"\7z.dll"); //路徑指向dll文件,此處dll放在與程序相同目錄,以下相同。
     	 
	}
	else    //64位操作系統(tǒng)
	{
    	SevenZipCompressor.SetLibraryPath(AppDomain.CurrentDomain.BaseDirectory + @"\7z64.dll");
	}
	using (var tmp = new SevenZipExtractor(“壓縮文件全名稱”))    //這里的全名稱包含路徑
    {
         tmp.ExtractArchive(“解壓到的路徑”);
    }

壓縮

偽代碼:

	if(IntPtr.Size == 4)    //32位操作系統(tǒng)
	{
     	 SevenZipCompressor.SetLibraryPath(AppDomain.CurrentDomain.BaseDirectory + @"\7z.dll");
	}
	else    //64位操作系統(tǒng)
	{
    	SevenZipCompressor.SetLibraryPath(AppDomain.CurrentDomain.BaseDirectory + @"\7z64.dll");
	}
	var compressor = new SevenZipCompressor();
	//壓縮文件夾:
	compressor.CompressDirectory(目錄名,壓縮文件名稱);//此處有多個(gè)重載,不一一列出。

	//壓縮文件:
	var zipTool = new SevenZipCompressor();
	zipTool.ArchiveFormat = OutArchiveFormat.Zip;   //壓縮文件類型
    string[] fileNames = {“文件全路徑”,“文件全路徑” }; //需要添加到壓縮文件的文件的全路徑數(shù)組。
    zipTool.CompressFiles(“壓縮文件名稱”, fileNames); //傳遞壓縮文件名稱,及文件全路徑數(shù)組。

以上就是C#使用SevenZipSharp實(shí)現(xiàn)壓縮文件和目錄的詳細(xì)內(nèi)容,更多關(guān)于C# SevenZipSharp壓縮的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • c# 常見文件路徑Api的使用示例

    c# 常見文件路徑Api的使用示例

    c#編程中經(jīng)常有遇到要處理文件路徑的需求,本文分別講述了如何從程序下面的文件和臨時(shí)目錄下的文件去使用路徑api,感興趣的朋友可以了解下
    2021-05-05
  • C/C++與Java各數(shù)據(jù)類型所占字節(jié)數(shù)的詳細(xì)比較

    C/C++與Java各數(shù)據(jù)類型所占字節(jié)數(shù)的詳細(xì)比較

    本篇文章主要是對(duì)C/C++與Java各數(shù)據(jù)類型所占字節(jié)數(shù)進(jìn)行了詳細(xì)的對(duì)比。需要的朋友可以過來參考下,希望對(duì)大家有所幫助
    2014-01-01
  • C#設(shè)計(jì)模式編程中運(yùn)用適配器模式結(jié)構(gòu)實(shí)戰(zhàn)演練

    C#設(shè)計(jì)模式編程中運(yùn)用適配器模式結(jié)構(gòu)實(shí)戰(zhàn)演練

    這篇文章主要介紹了C#設(shè)計(jì)模式編程中運(yùn)用適配器模式結(jié)構(gòu)實(shí)戰(zhàn)演練,并總結(jié)了適配器模式的優(yōu)缺點(diǎn)和適用場(chǎng)景以及.NET框架中的應(yīng)用,需要的朋友可以參考下
    2016-02-02
  • Unity封裝延時(shí)調(diào)用定時(shí)器

    Unity封裝延時(shí)調(diào)用定時(shí)器

    這篇文章主要為大家詳細(xì)介紹了Unity封裝延時(shí)調(diào)用定時(shí)器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • C#無損高質(zhì)量壓縮圖片代碼

    C#無損高質(zhì)量壓縮圖片代碼

    這篇文章主要為大家詳細(xì)介紹了C#無損高質(zhì)量壓縮圖片代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • C#中is與as的區(qū)別分析

    C#中is與as的區(qū)別分析

    這篇文章主要介紹了C#中is與as的區(qū)別,較為詳細(xì)的分析了is與as的原理與特性及用法區(qū)別,具有很好的學(xué)習(xí)借鑒價(jià)值,需要的朋友可以參考下
    2014-10-10
  • C#文件合并的方法

    C#文件合并的方法

    這篇文章主要介紹了C#文件合并的方法,實(shí)例分析了C#基于FileStream操作文件合并的相關(guān)技巧,需要的朋友可以參考下
    2015-07-07
  • C# winfroms使用socket客戶端服務(wù)端的示例代碼

    C# winfroms使用socket客戶端服務(wù)端的示例代碼

    這篇文章主要為大家詳細(xì)介紹了C# winfroms使用socket客戶端服務(wù)端的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-02-02
  • 利用C#操作WMI指南

    利用C#操作WMI指南

    WMI提供了一套內(nèi)置在Microsoft Windows操作系統(tǒng)中的豐富的系統(tǒng)管理服務(wù),可以在有大量的應(yīng)用程序、服務(wù)和設(shè)備的系統(tǒng)中提供全方位的管理功能。它允許應(yīng)用程序的開發(fā)者,使用簡(jiǎn)單的、一致的機(jī)制,去查詢企業(yè)中的任一臺(tái)計(jì)算機(jī)上的信息,或是進(jìn)行系統(tǒng)配置
    2016-11-11
  • WPF在VisualTree上增加Visual

    WPF在VisualTree上增加Visual

    這篇文章介紹了WPF在VisualTree上增加Visual的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-06-06

最新評(píng)論