C# 解壓zip文件,大家經常用的是ICSharpCode.SharpZipLib.dll,ZipInputStream,去操作zip文件,今天博主也遇到了這個問題,這邊先和大家交流我是怎麼解決的
首先如果是普通的Stored和Deflated,這邊采用ZipInputStream解決
using (var s = new ZipInputStream(File.OpenRead("")))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.IsDirectory)
{
continue;
}
string directorName = Path.Combine("", Path.GetDirectoryName(theEntry.Name));
string fileName = Path.Combine(directorName, Path.GetFileName(theEntry.Name));
if (!Directory.Exists(directorName))
{
Directory.CreateDirectory(directorName);
}
if (!String.IsNullOrEmpty(fileName))
{
using (FileStream streamWriter = File.Create(fileName))
{
int size = 4096;
byte[] data = new byte[size];
while (size > 0)
{
streamWriter.Write(data, 0, size);
size = s.Read(data, 0, data.Length);
}
}
}
}
}
Deflate64,BZip2,WinZipAES等壓縮方式
如果出現Deflate64,BZip2,WinZipAES等壓縮方式,就非常麻煩,ZipInputStream解決不了,博主的解決方案是調用本地的winRar處理這個問題
public class WinRARHelper
{
/// <summary>
/// 是否安裝了Winrar
/// </summary>
/// <returns></returns>
static public bool Exists()
{
RegistryKey the_Reg = Registry.LocalMachine.
OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\AppPaths\WinRAR.exe");
return !string.IsNullOrEmpty(the_Reg.GetValue("").ToString());
}
/// 解壓
/// </summary>
/// <param name="unRarPatch"></param>
/// <param name="rarPatch"></param>
/// <param name="rarName"></param>
/// <returns></returns>
public bool unCompressRAR(string unRarPatch, string rarPatch, string rarName)
{
string the_rar;
RegistryKey the_Reg;
object the_Obj;
string the_Info;
try
{
the_Reg = Registry.LocalMachine.
OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
the_Obj = the_Reg.GetValue("");
the_rar = the_Obj.ToString();
the_Reg.Close();
if (Directory.Exists(unRarPatch) == false)
{
Directory.CreateDirectory(unRarPatch);
}
the_Info = "x " + rarName + " " + unRarPatch + " -y";
ProcessStartInfo the_StartInfo = new ProcessStartInfo();
the_StartInfo.FileName = the_rar;
the_StartInfo.Arguments = the_Info;
the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
the_StartInfo.WorkingDirectory = rarPatch;//獲取壓縮包路徑
Process the_Process = new Process();
the_Process.StartInfo = the_StartInfo;
the_Process.Start();
the_Process.WaitForExit();
the_Process.Close();
}
catch (Exception ex)
{
throw ex;
}
return true;
}
}
完美解決問題。