public static class Tar32
{
[DllImport("tar32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
static extern int Tar(IntPtr _hwnd, string _szCmdLine, StringBuilder _szOutput, int _dwSize);
/// <summary>
/// TAR 压缩文件作成
/// </summary>
/// <param name="asDestinationFilePath">作成tar压缩文件名</param>
/// <param name="abCompress">是否压缩
/// false 为不压缩扩展名为.tar的文件
/// true 指定为gzip圧縮 (.tar.gz)的文件作成。
/// </param>
/// <param name="asSourceFilePaths">压缩对象文件名</param>
/// <returns>TAR 压缩文件创建作成正常结束的场合 true</returns>
public static bool CreateTarAndGz(
string asDestinationFilePath,
bool abCompress,
string[] asSourceFilePaths)
{
string sCmd = @"-c ";
if (abCompress)
{
sCmd += @"-z ";
}
sCmd += @"--use-directory=0 ";
sCmd += asDestinationFilePath + @" ";
for (int i = 0; i < asSourceFilePaths.Length; i++)
{
sCmd += asSourceFilePaths[i] + @" ";
}
int iRet = Tar(IntPtr.Zero, sCmd, null, 0);
if (iRet != 0)
{
return false;
}
return true;
}
}
使用方法
private bool CompressFile(string psFileName){
//Tar,GZ文件保存的文件及作成文件
string wPath=@"F:\\UPLOAD";
if (wPath.Substring(wPath.Length - 1, 1) != "\\")
{
wPath = wPath + "\\";
}
try
{
DirectoryInfo di = new DirectoryInfo(wPath);
if (!di.Exists)
{
di.Create();
}
}
//TAR,Gz压缩文件的名称
string sCompFileFullName = wPath + "\\" + psFileName + ".tar";
List<string> sFilenames = new List<string>();
//圧縮前文件读入
string sFromFilePath =@"F:\\"+ psFileName;
DirectoryInfo di = new DirectoryInfo(sFromFilePath);
if (!di.Exists)
{
return false;
}
string[] FileNames = Directory.GetFiles(sFromFilePath);
foreach (string tempFileName in FileNames)
{
sFilenames.Add(tempFileName);
}
bool bResult = Tar32.Create(sCompFileFullName, false, sFilenames.ToArray());
if(!bResult)
{
return false;
}
return true;
}