為了便于檔案在網絡中的傳輸和儲存,通常将檔案進行壓縮操作,常用的壓縮格式有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 = @"SOFTWAREMicrosoftWindowsCurrentVersionApp PathsWinRAR.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 = @"SOFTWAREMicrosoftWindowsCurrentVersionApp PathsWinRAR.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 = @"SOFTWAREMicrosoftWindowsCurrentVersionApp PathsWinRAR.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, @"folder1folder2folder3file2.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: est", @"e: est est.zip"); //壓縮
System.IO.Compression.ZipFile.ExtractToDirectory(@"e: est est.zip", @"e: est"); //解壓
支援格式最多的C#解壓縮開源庫
當您還苦苦在為上面的各種壓縮格式發愁的時候,一個名為SharpCompress的C#架構被開源,您可以在搜尋引擎中找到SharpCompress架構的開源代碼,它支援:rar 7zip, zip, tar, tzip和bzip2格式的壓縮和解壓,下面的示例直接從rar格式檔案讀取并解壓檔案。
using (Stream stream = File.OpenRead(@"C:Codesharpcompress.rar"))
{
var reader = ReaderFactory.Open(stream);
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
Console.WriteLine(reader.Entry.FilePath);
reader.WriteEntryToDirectory(@"C: emp");
}
}
}
零度最後的總結
關于rar和zip格式相比,rar的壓縮率比zip要高,而且支援分卷壓縮,但rar是商業軟體,需要付費,zip壓縮率不如rar那麼高,但開源免費,7zip格式開源免費,壓縮率較為滿意,這些壓縮格式各有優勢,就微軟平台和一些開源平台來說,一般采用的都是zip格式,因為它更容易通過程式設計的方式實作,比rar更加可靠,以上就是零度為您推薦的C#解壓縮架構,感謝閱讀,希望對您有所幫助。
http://www.tugberkugurlu.com/archive/net-4-5-to-support-zip-file-manipulation-out-of-the-box
https://github.com/adamhathcock/sharpcompress