C#文件壓縮:ICSharpCode.SharpZipLib生成zip、tar、tar.gz


原文地址:https://blog.csdn.net/nihao198503/article/details/9204115

將代碼原封不動的copy過來,只是因為有關tar的文章太少,大多都是zip的文章

/// <summary>  
/// 生成 ***.tar.gz 文件  
/// </summary>  
/// <param name="strBasePath">文件基目錄(源文件、生成文件所在目錄)</param>  
/// <param name="strSourceFolderName">待壓縮的源文件夾名</param>  
public bool CreatTarGzArchive(string strBasePath, string strSourceFolderName)  
{  
    if (string.IsNullOrEmpty(strBasePath)  
        || string.IsNullOrEmpty(strSourceFolderName)  
        || !System.IO.Directory.Exists(strBasePath)  
        || !System.IO.Directory.Exists(Path.Combine(strBasePath, strSourceFolderName)))  
    {  
        return false;  
    }  
  
    Environment.CurrentDirectory = strBasePath;  
    string strSourceFolderAllPath = Path.Combine(strBasePath, strSourceFolderName);  
    string strOupFileAllPath = Path.Combine(strBasePath, strSourceFolderName + ".tar.gz");  
  
    Stream outTmpStream = new FileStream(strOupFileAllPath, FileMode.OpenOrCreate);  
  
    //注意此處源文件大小大於4096KB  
    Stream outStream = new GZipOutputStream(outTmpStream);  
    TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor);  
    TarEntry entry = TarEntry.CreateEntryFromFile(strSourceFolderAllPath);  
    archive.WriteEntry(entry, true);  
  
    if (archive != null)  
    {  
        archive.Close();  
    }  
  
    outTmpStream.Close();  
    outStream.Close();  
  
    return true;  
}  
生成 ***.tar.gz 文件

 

        /// <summary>
        /// 文件解壓
        /// </summary>
        /// <param name="zipPath">壓縮文件路徑</param>
        /// <param name="goalFolder">解壓到的目錄</param>
        /// <returns></returns>
        public 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)
            {
                Console.WriteLine("壓縮出錯!");
                return false;
            }
            finally
            {
                if (null != tarArchive) tarArchive.Close();
                if (null != gzipStream) gzipStream.Close();
                if (null != inStream) inStream.Close();
            }
        }
tar.gz解壓

 

/// <summary>  
/// 生成 ***.tar 文件  
/// </summary>  
/// <param name="strBasePath">文件基目錄(源文件、生成文件所在目錄)</param>  
/// <param name="strSourceFolderName">待壓縮的源文件夾名</param>  
public bool CreatTarArchive(string strBasePath, string strSourceFolderName)  
{  
    if (string.IsNullOrEmpty(strBasePath)  
        || string.IsNullOrEmpty(strSourceFolderName)  
        || !System.IO.Directory.Exists(strBasePath)  
        || !System.IO.Directory.Exists(Path.Combine(strBasePath, strSourceFolderName)))  
    {  
        return false;  
    }  
  
    Environment.CurrentDirectory = strBasePath;  
    string strSourceFolderAllPath = Path.Combine(strBasePath, strSourceFolderName);  
    string strOupFileAllPath = Path.Combine(strBasePath, strSourceFolderName + ".tar");  
  
    Stream outStream = new FileStream(strOupFileAllPath, FileMode.OpenOrCreate);  
  
    TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor);  
    TarEntry entry = TarEntry.CreateEntryFromFile(strSourceFolderAllPath);  
    archive.WriteEntry(entry, true);  
  
    if (archive != null)  
    {  
        archive.Close();  
    }  
  
    outStream.Close();  
  
    return true;  
}  
生成 ***.tar文件(針對文件夾)

 

        /// <summary>
        /// 生成tar文件
        /// </summary>
        /// <param name="strBasePath">文件夾路徑——將被壓縮的文件所在的地方</param>        
        /// <param name="listFilesPath">文件的路徑:H:\Demo\xxx.txt</param>
        /// <param name="tarFileName">壓縮后tar文件名稱</param>
        /// <returns></returns>
        public static bool CreatTarArchive(string strBasePath, List<string> listFilesPath, string tarFileName)//"20180524" + ".tar"
        {
            if (string.IsNullOrEmpty(strBasePath) || string.IsNullOrEmpty(tarFileName) || !System.IO.Directory.Exists(strBasePath))
                return false;

            Environment.CurrentDirectory = strBasePath;
            string strOupFileAllPath = strBasePath + tarFileName;//一個完整的文件路徑 .tar
            Stream outStream = new FileStream(strOupFileAllPath, FileMode.OpenOrCreate);//打開.tar文件
            TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor);

            for (int i = 0; i < listFilesPath.Count; i++)
            {
                string fileName = listFilesPath[i];
                TarEntry entry = TarEntry.CreateEntryFromFile(fileName);//將文件寫到.tar文件中去
                archive.WriteEntry(entry, true);
            }

            if (archive != null)
            {
                archive.Close();
            }

            outStream.Close();

            return true;
        }
生成tar文件(針對於多個文件)

 

/// <summary>  
/// tar包解壓  
/// </summary>  
/// <param name="strFilePath">tar包路徑</param>  
/// <param name="strUnpackDir">解壓到的目錄</param>  
/// <returns></returns>  
public static bool UnpackTarFiles(string strFilePath, string strUnpackDir)  
{  
    try  
    {  
        if (!File.Exists(strFilePath))  
        {  
            return false;  
        }  
  
        strUnpackDir = strUnpackDir.Replace("/", "\\");  
        if (!strUnpackDir.EndsWith("\\"))  
        {  
            strUnpackDir += "\\";  
        }  
  
        if (!Directory.Exists(strUnpackDir))  
        {  
            Directory.CreateDirectory(strUnpackDir);  
        }  
  
        FileStream fr = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);  
        DhcEc.SharpZipLib.Tar.TarInputStream s = new DhcEc.SharpZipLib.Tar.TarInputStream(fr);  
        DhcEc.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();  
  
        return true;  
    }  
    catch (Exception)  
    {  
        return false;  
    }  
} 
tar包解壓

 

/// <summary>  
/// zip壓縮文件  
/// </summary>  
/// <param name="filename">filename生成的文件的名稱,如:C\123\123.zip</param>  
/// <param name="directory">directory要壓縮的文件夾路徑</param>  
/// <returns></returns>  
public static bool PackFiles(string filename, string directory)  
{  
    try  
    {  
        directory = directory.Replace("/", "\\");  
  
        if (!directory.EndsWith("\\"))  
            directory += "\\";  
        if (!Directory.Exists(directory))  
        {  
            Directory.CreateDirectory(directory);  
        }  
        if (File.Exists(filename))  
        {  
            File.Delete(filename);  
        }  
  
        FastZip fz = new FastZip();  
        fz.CreateEmptyDirectories = true;  
        fz.CreateZip(filename, directory, true, "");  
  
        return true;  
    }  
    catch (Exception)  
    {  
        return false;  
    }  
} 
zip壓縮文件

 

/// <summary>  
/// zip解壓文件  
/// </summary>  
/// <param name="file">壓縮文件的名稱,如:C:\123\123.zip</param>  
/// <param name="dir">dir要解壓的文件夾路徑</param>  
/// <returns></returns>  
public static bool UnpackFiles(string file, string dir)  
{  
    try  
    {  
        if (!File.Exists(file))  
            return false;  
  
        dir = dir.Replace("/", "\\");  
        if (!dir.EndsWith("\\"))  
            dir += "\\";  
  
        if (!Directory.Exists(dir))  
            Directory.CreateDirectory(dir);  
  
        FileStream fr = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);  
        DhcEc.SharpZipLib.Zip.ZipInputStream s = new DhcEc.SharpZipLib.Zip.ZipInputStream(fr);  
        DhcEc.SharpZipLib.Zip.ZipEntry theEntry;  
        while ((theEntry = s.GetNextEntry()) != null)  
        {  
            string directoryName = Path.GetDirectoryName(theEntry.Name);  
            string fileName = Path.GetFileName(theEntry.Name);  
  
            if (directoryName != String.Empty)  
                Directory.CreateDirectory(dir + directoryName);  
  
            if (fileName != String.Empty)  
            {  
                FileStream streamWriter = File.Create(dir + 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();  
  
        return true;  
    }  
    catch (Exception)  
    {  
        return false;  
    }  
}
zip解壓文件

 

 /// <summary>
        /// 壓縮文件夾
        /// </summary>
        /// <param name="DirectoryToZip">需要壓縮的文件夾(絕對路徑)</param>
        /// <param name="ZipedPath">壓縮后的文件路徑(絕對路徑)</param>
        /// <param name="ZipedFileName">>壓縮后的文件名稱(文件名,默認 同源文件夾同名)</param>
        public static void ZipDirectory(string DirectoryToZip, string ZipedPath, string ZipedFileName = "")
        {
            //如果目錄不存在,則報錯
            if (!System.IO.Directory.Exists(DirectoryToZip))
            {
                throw new System.IO.FileNotFoundException("指定的目錄: " + DirectoryToZip + " 不存在!");
            }
            //文件名稱(默認同源文件名稱相同)
            string ZipFileName = string.IsNullOrEmpty(ZipedFileName) ? ZipedPath + "\\" + new DirectoryInfo(DirectoryToZip).Name + ".zip" : ZipedPath + "\\" + ZipedFileName + ".zip";
            using (System.IO.FileStream ZipFile = System.IO.File.Create(ZipFileName))
            {
                using (ZipOutputStream s = new ZipOutputStream(ZipFile))
                {
                    ZipSetp(DirectoryToZip, s, "");
                }
            }
        }



        /// <summary>
        /// 遞歸遍歷目錄        
        /// </summary>
        private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath)
        {
            if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)
            {
                strDirectory += Path.DirectorySeparatorChar;
            }
            Crc32 crc = new Crc32();
            string[] filenames = Directory.GetFileSystemEntries(strDirectory);
            foreach (string file in filenames)// 遍歷所有的文件和目錄
            {
                if (Directory.Exists(file))// 先當作目錄處理如果存在這個目錄就遞歸Copy該目錄下面的文件
                {
                    string pPath = parentPath;
                    pPath += file.Substring(file.LastIndexOf("\\") + 1);
                    pPath += "\\";
                    ZipSetp(file, s, pPath);
                }
                else // 否則直接壓縮文件
                {
                    //打開壓縮文件
                    using (FileStream fs = File.OpenRead(file))
                    {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        string fileName = parentPath + file.Substring(file.LastIndexOf("\\") + 1);
                        ZipEntry entry = new ZipEntry(fileName);
                        entry.DateTime = DateTime.Now;
                        entry.Size = fs.Length;
                        fs.Close();
                        crc.Reset();
                        crc.Update(buffer);
                        entry.Crc = crc.Value;
                        s.PutNextEntry(entry);
                        s.Write(buffer, 0, buffer.Length);
                    }
                }
            }
        }
將文件夾壓縮成zip

 

使用C#自帶類庫對單個文件進行解壓縮(rar)

        public void YaSuo()
        {
            using (FileStream fsRead = File.OpenRead(@"F:\MVC5_Demo\Project4YaSuo\Project4YaSuo\Files\筆記.txt"))
            {
                //創建寫入文件的流
                using (FileStream fsWrite = File.OpenWrite(@"F:\MVC5_Demo\Project4YaSuo\Project4YaSuo\Files\yasuo.rar"))
                {
                    //創建壓縮流
                    using (GZipStream zipStream = new GZipStream(fsWrite, CompressionMode.Compress))
                    {
                        //每次讀取1024byte
                        byte[] byts = new byte[1024 * 10];
                        int len = 0;
                        while ((len = fsRead.Read(byts, 0, byts.Length)) > 0)
                        {
                            zipStream.Write(byts, 0, len);//通過壓縮流寫入文件
                        }
                    }
                }
            }
        }
壓縮成rar文件

 

        public void JieYa()
        {
            //讀取壓縮文件
            using (FileStream fsRead = File.OpenRead(@"F:\MVC5_Demo\Project4YaSuo\Project4YaSuo\Files\yasuo.rar"))
            {
                //創建壓縮流
                using (GZipStream gzipStream = new GZipStream(fsRead, CompressionMode.Decompress))
                {
                    using (FileStream fsWrite = File.OpenWrite(@"F:\MVC5_Demo\Project4YaSuo\Project4YaSuo\Files\筆記.txt"))
                    {
                        byte[] byts = new byte[1024 * 10];
                        int len = 0;
                        //寫入新文件
                        while ((len = gzipStream.Read(byts, 0, byts.Length)) > 0)
                        {
                            fsWrite.Write(byts, 0, len);
                        }
                    }

                }
            }
        }
解壓

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM