利用tar32.dll实现压缩成.tar.gz文件

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值