C# 解/壓縮rar/zip格式文件

爲了便於文件在網絡中的傳輸和保存,通常將文件進行壓縮操作,常用的壓縮格式有rar、zip和7z。
本文將介紹在C#中如何對這幾種類型的文件進行壓縮和解壓,並提供一些在C#中解壓縮文件的開源庫。

在C#.NET中壓縮解壓rar文件

rar格式是一種具有專利文件的壓縮格式,是一種商業壓縮格式,不開源,對解碼算法是公開的,但壓縮算法是私有的,需要付費,如果需要在您的商業軟件中使用rar格式進行解壓縮,那麼你需要爲rar付費,rar在國內很流行是由於盜版的存在,正因爲算法是不開源的,所以我們壓縮rar並沒有第三方的開源庫可供選擇,只能另尋出路。

針對rar的解壓縮,我們通常使用winrar,幾乎每臺機器都安裝了winrar,對於普通用戶來說它提供基於用戶界面的解壓縮方式,另外,它也提供基於命令行的解壓縮方式,這爲我們在程序中解壓縮rar格式提供了一個入口,我們可以在C#程序中調用rar的命令行程序實現解壓縮,思路是這樣的:

1、判斷註冊表確認用戶機器是否安裝winrar程序,如果安裝取回winrar安裝目錄。

2、創建一個命令行執行進程。

3、通過winrar的命令行參數實現解壓縮。

首先我們通過下面的代碼判斷用戶計算機是否安裝了winrar壓縮工具:

如果已經安裝winrar可通過如下代碼返回winrar的安裝位置,未安裝則返回空字符串,最後並關閉註冊表:

public static string ExistsWinRar()
{
    string result = string.Empty;

    string key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe";
    RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(key);
    if (registryKey != null)
    {
        result = registryKey.GetValue("").ToString();
    }
    registryKey.Close();

    return result;
}
/// <summary>
/// 將格式爲rar的壓縮文件解壓到指定的目錄
/// </summary>
/// <param name="rarFileName">要解壓rar文件的路徑</param>
/// <param name="saveDir">解壓後要保存到的目錄</param>
public static void DeCompressRar(string rarFileName, string saveDir)
{
    string regKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe";
    RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(regKey);
    string winrarPath = registryKey.GetValue("").ToString();
    registryKey.Close();
    string winrarDir = System.IO.Path.GetDirectoryName(winrarPath);
    String commandOptions = string.Format("x {0} {1} -y", rarFileName, saveDir);

    ProcessStartInfo processStartInfo = new ProcessStartInfo();
    processStartInfo.FileName = System.IO.Path.Combine(winrarDir, "rar.exe");
    processStartInfo.Arguments = commandOptions;
    processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

    Process process = new Process();
    process.StartInfo = processStartInfo;
    process.Start();
    process.WaitForExit();
    process.Close();
}
/// <summary>
/// 將目錄和文件壓縮爲rar格式並保存到指定的目錄
/// </summary>
/// <param name="soruceDir">要壓縮的文件夾目錄</param>
/// <param name="rarFileName">壓縮後的rar保存路徑</param>
public static void CompressRar(string soruceDir, string rarFileName)
{
    string regKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe";
    RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(regKey);
    string winrarPath = registryKey.GetValue("").ToString();
    registryKey.Close();
    string winrarDir = System.IO.Path.GetDirectoryName(winrarPath);
    String commandOptions = string.Format("a {0} {1} -r", rarFileName, soruceDir);

    ProcessStartInfo processStartInfo = new ProcessStartInfo();
    processStartInfo.FileName = System.IO.Path.Combine(winrarDir, "rar.exe");
    processStartInfo.Arguments = commandOptions;
    processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    Process process = new Process();
    process.StartInfo = processStartInfo;
    process.Start();
    process.WaitForExit();
    process.Close();
}

在C#.NET中壓縮解壓zip文件

zip是一種免費開源的壓縮格式,windows平臺自帶zip壓縮和解壓工具,由於算法是開源的,所以基於zip的解壓縮開源庫也很多,SharpZipLib是一個很不錯的C#庫,它能夠解壓縮zip、gzip和tar格式的文件,首先下載SharpZipLib解壓後,在您的項目中引用ICSharpCode.SharpZLib.dll程序集即可,下面是一些關於SharpZipLib壓縮和解壓的示例。

ZipOutputStream zipOutStream = new ZipOutputStream(File.Create("my.zip"));
CreateFileZipEntry(zipOutStream, "file1.txt", "file1.txt");
CreateFileZipEntry(zipOutStream, @"folder1\folder2\folder3\file2.txt", "file2.txt");
zipOutStream.Close();
Directory.CreateDirectory("ZipOutPut");
 ZipInputStream zipInputStream = new ZipInputStream(File.Open("my.zip", FileMode.Open));
 ZipEntry zipEntryFromZippedFile = zipInputStream.GetNextEntry();
 while (zipEntryFromZippedFile != null)
 {
     if (zipEntryFromZippedFile.IsFile)
     {
         FileInfo fInfo = new FileInfo(string.Format("ZipOutPut\\{0}", zipEntryFromZippedFile.Name));
         if (!fInfo.Directory.Exists) fInfo.Directory.Create();

         FileStream file = fInfo.Create();
         byte[] bufferFromZip = new byte[zipInputStream.Length];
         zipInputStream.Read(bufferFromZip, 0, bufferFromZip.Length);
         file.Write(bufferFromZip, 0, bufferFromZip.Length);
         file.Close();
     }
     zipEntryFromZippedFile = zipInputStream.GetNextEntry();
 }
 zipInputStream.Close();

使用.NET中自帶的類解壓縮zip文件

微軟在System.IO.Compression命名空間有一些關於文件解壓縮的類,如果只是希望壓縮解壓zip和gzip格式的文件,是個不錯的選擇,在NET Framework 4.5框架中,原生System.IO.Compression.FileSystem.dll程序集中新增了一個名爲ZipFile的類,,讓壓縮和解壓zip文件變得更簡單,ZipFile的使用示例如下:

System.IO.Compression.ZipFile.CreateFromDirectory(@"e:\test", @"e:\test\test.zip"); //壓縮
System.IO.Compression.ZipFile.ExtractToDirectory(@"e:\test\test.zip", @"e:\test"); //解壓

支持格式最多的C#解壓縮開源庫

當您還苦苦在爲上面的各種壓縮格式發愁的時候,一個名爲SharpCompress的C#框架被開源,您可以在搜索引擎中找到SharpCompress框架的開源代碼,它支持:rar 7zip, zip, tar, tzip和bzip2格式的壓縮和解壓,下面的示例直接從rar格式文件讀取並解壓文件。

using (Stream stream = File.OpenRead(@"C:\Code\sharpcompress.rar"))
{
    var reader = ReaderFactory.Open(stream);
    while (reader.MoveToNextEntry())
    {
        if (!reader.Entry.IsDirectory)
        {
            Console.WriteLine(reader.Entry.FilePath);
            reader.WriteEntryToDirectory(@"C:\temp");
        }
    }
}

總結

關於rar和zip格式相比,rar的壓縮率比zip要高,而且支持分卷壓縮,但rar是商業軟件,需要付費,zip壓縮率不如rar那麼高,但開源免費,7zip格式開源免費,壓縮率較爲滿意,這些壓縮格式各有優勢,就微軟平臺和一些開源平臺來說,一般採用的都是zip格式,因爲它更容易通過編程的方式實現,比rar更加可靠。感謝閱讀,希望對您能有所幫助。

特別感謝零度編程分享!(小輝只是用來知識學習與分享,如有侵權,聯繫刪除,謝謝!)

摘自零度編程。源鏈接:https://www.xcode.me/more/csharp-compression-zip-rar

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章