c# 解壓 處理.tar.gz檔案
tar是把檔案打成一個包,並不壓縮;
gz是用gzip把打成包的.tar檔案壓縮;
過程是
先 在ICSharpCode.SharpZipLib.GZip 中的方法解壓為tar檔案包,
///////////
var targzpath="xxx/xxx/xxx.tar.gz";
GZipInputStream gzs = new GZipInputStream(targzpath);
FileStream destFile = File.Open("xxx/xxx/xxx", FileMode.Create);
int buffersize = 2048;//緩衝區的尺寸,一般是2048的倍數
byte[] FileData = new byte[buffersize];//建立緩衝資料
while (buffersize > 0)//一直讀取到檔案末尾
{
buffersize = gzs.Read(FileData, 0, buffersize);//讀取壓縮檔案資料
destFile.Write(FileData, 0, buffersize);//寫入目標檔案
}
destFile.Close();//關閉目標檔案
gzs.Close();
再用 using ICSharpCode.SharpZipLib.Tar; 裡方法 還原為檔案
/////////////////////////////
FileStream fr = new FileStream("xxx/xxx/xxx.tar", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
ICSharpCode.SharpZipLib.Tar.TarInputStream s = new ICSharpCode.SharpZipLib.Tar.TarInputStream(fr);
ICSharpCode.SharpZipLib.Tar.TarEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (directoryName != String.Empty)
Directory.CreateDirectory(strUnpackDir + directoryName);//解壓到 資料夾
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(strUnpackDir + theEntry.Name);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
fr.Close();
要新增引用:
ICSharpCode.SharpZipLib
自己網上找找-------
-------------------------------------------------------------------
好像這樣更簡單
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
/// <summary>
/// 檔案解壓
/// </summary>
/// <param name="zipPath">壓縮檔案路徑</param>
/// <param name="goalFolder">解壓到的目錄</param>
/// <returns></returns>
internal static bool UnzipTgz(string zipPath, string goalFolder)
{
Stream inStream = null;
Stream gzipStream = null;
TarArchive tarArchive = null;
try
{
using (inStream = File.OpenRead(zipPath))
{
using (gzipStream = new GZipInputStream(inStream))
{
tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
tarArchive.ExtractContents(goalFolder);
tarArchive.Close();
}
}
return true;
}
catch (Exception ex)
{
LogManager.GetCurrentClassLogger().Error(ex);
return false;
}
finally
{
if (null != tarArchive) tarArchive.Close();
if (null != gzipStream) gzipStream.Close();
if (null != inStream) inStream.Close();
}
}