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);
                        }
                    }

                }
            }
        }

解压

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ICSharpCode.SharpZipLib.Zip是一个用于处理压缩文件的库。它提供了创建、读取和修改压缩文件的功能。通过添加ICSharpCode.SharpZipLib.Zip的引用,你可以在你的代码中使用该库提供的类和方法来进行压缩和解压缩操作。这个库支持多种压缩格式,包括ZipGZip、BZip2和Tar。要使用ICSharpCode.SharpZipLib.Zip进行压缩操作,你可以使用ZipFile.Create方法创建一个压缩文件对象,然后使用Add方法将文件添加到压缩文件中,最后使用CommitUpdate方法提交更新并关闭压缩文件。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [ICSharpCode.SharpZipLi 压缩、解压文件 附源码](https://blog.csdn.net/baipai8449/article/details/101974369)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [完美解决利用ICSharpCode.SharpZipLib.Zip文件夹进行压缩压缩后目录过长的问题](https://blog.csdn.net/qq_40241060/article/details/127887806)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值