C#使用SevenZipSharp實(shí)現(xiàn)壓縮文件和目錄
C#使用SevenZipSharp的操作
封裝了一個類,方便使用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è)這是某個類中的一個事件定義
public event EventHandler<ProgressEventArgs> ProgressUpdated = null;
public static bool SetSetLibraryPath()
{
//設(shè)置庫路徑
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è)置壓縮級別和檔案格式
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
// 這里簡單地返回 false,但你可以根據(jù)需要更改此行為
Console.WriteLine($"壓縮文件時(shí)發(fā)生錯誤: {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è)置壓縮級別和檔案格式
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
// 這里簡單地返回 false,但你可以根據(jù)需要更改此行為
Console.WriteLine($"壓縮文件時(shí)發(fā)生錯誤: {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è)置庫
if (!SevenZipSharpUser.SetSetLibraryPath())
{
MessageBox.Show("7z.dll庫引用失敗!", "錯誤!", 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壓縮解壓文件
首先程序需要用到三個DLL文件,分別是:SevenZipSharp.dll、7z.dll、7z64.dll,其中SevenZipSharp.dll需要程序進(jìn)行引用,而其他兩個文件給代碼使用,其中7z.dll是32位,7z64.dll是64位的。(此處需要注意,這里的32位與64位指的是程序,而不是操作系統(tǒng),即指的是VS中右鍵項(xiàng)目屬性里的目標(biāo)平臺,可由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(目錄名,壓縮文件名稱);//此處有多個重載,不一一列出。
//壓縮文件:
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壓縮的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C/C++與Java各數(shù)據(jù)類型所占字節(jié)數(shù)的詳細(xì)比較
本篇文章主要是對C/C++與Java各數(shù)據(jù)類型所占字節(jié)數(shù)進(jìn)行了詳細(xì)的對比。需要的朋友可以過來參考下,希望對大家有所幫助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)演練,并總結(jié)了適配器模式的優(yōu)缺點(diǎn)和適用場景以及.NET框架中的應(yīng)用,需要的朋友可以參考下2016-02-02
Unity封裝延時(shí)調(diào)用定時(shí)器
這篇文章主要為大家詳細(xì)介紹了Unity封裝延時(shí)調(diào)用定時(shí)器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
C# winfroms使用socket客戶端服務(wù)端的示例代碼
這篇文章主要為大家詳細(xì)介紹了C# winfroms使用socket客戶端服務(wù)端的相關(guān)知識,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-02-02

