C#压缩解压缩文件(zip格式)

Wesley13
• 阅读 600
using System;
using System.Collections.Generic;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace TestConsole
{
    internal class Program
    {
        private static void Main()
        {
            //CreateZipFile(@"d:\", @"d:\a.zip");
            UnZipFile(@"E:\我的桌面.zip"); 
            Console.Read();
        }

        /// <summary>
        ///     压缩文件为zip包
        /// </summary>
        /// <param name="filesPath"></param>
        /// <param name="zipFilePath"></param>
        private static bool CreateZipFile(string filesPath, string zipFilePath)
        {
            if (!Directory.Exists(filesPath))
            {
                return false;
            }

            try
            {
                string[] filenames = Directory.GetFiles(filesPath);
                using (var s = new ZipOutputStream(File.Create(zipFilePath)))
                {
                    s.SetLevel(9); // 压缩级别 0-9
                    //s.Password = "123"; //Zip压缩文件密码
                    var buffer = new byte[4096]; //缓冲区大小
                    foreach (string file in filenames)
                    {
                        var entry = new ZipEntry(Path.GetFileName(file));
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);
                        using (FileStream fs = File.OpenRead(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }
                    s.Finish();
                    s.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception during processing {0}", ex);
            }
            return false;
        }

        /// <summary>
        ///     文件解压(zip格式)
        /// </summary>
        /// <param name="zipFilePath"></param>
        /// <returns></returns>
        private static List<FileInfo> UnZipFile(string zipFilePath)
        {
            var files = new List<FileInfo>();
            var zipFile = new FileInfo(zipFilePath);
            if (!File.Exists(zipFilePath))
            {
                return files;
            }
            using (var zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath)))
            {
                ZipEntry theEntry;
                while ((theEntry = zipInputStream.GetNextEntry()) != null)
                {
                    if (zipFilePath != null)
                    {
                        string dir = Path.GetDirectoryName(zipFilePath);
                        if (dir != null)
                        {
                            string dirName = Path.Combine(dir, zipFile.Name.Replace(zipFile.Extension, ""));
                            string fileName = Path.GetFileName(theEntry.Name);

                            if (!string.IsNullOrEmpty(dirName))
                            {
                                if (!Directory.Exists(dirName))
                                {
                                    Directory.CreateDirectory(dirName);
                                }
                            }
                            if (!string.IsNullOrEmpty(fileName))
                            {
                                string filePath = Path.Combine(dirName, theEntry.Name);
                                using (FileStream streamWriter = File.Create(filePath))
                                {
                                    var data = new byte[2048];
                                    while (true)
                                    {
                                        int size = zipInputStream.Read(data, 0, data.Length);
                                        if (size > 0)
                                        {
                                            streamWriter.Write(data, 0, size);
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                                files.Add(new FileInfo(filePath));
                            }
                        }
                    }
                }
            }
            return files;
        }
    }
}

/// <summary>
        ///     文件解压(Rar格式)
        /// </summary>
        /// <param name="rarFilePath"></param>
        /// <returns></returns>
        public static List<FileInfo> UnRarFile(string rarFilePath)
        {
            var files = new List<FileInfo>();
            var fileInput = new FileInfo(rarFilePath);
            if (fileInput.Directory != null)
            {
                string dirName = Path.Combine(fileInput.Directory.FullName,
                                              fileInput.Name.Replace(fileInput.Extension, ""));

                if (!string.IsNullOrEmpty(dirName))
                {
                    if (!Directory.Exists(dirName))
                    {
                        Directory.CreateDirectory(dirName);
                    }
                }
                dirName = dirName.EndsWith("\\") ? dirName : dirName + "\\"; //最后这个斜杠不能少!
                string shellArguments = string.Format("x -o+ {0} {1}", rarFilePath, dirName);
                using (var unrar = new Process())
                {
                    unrar.StartInfo.FileName = @"C:\Program Files\WinRAR\WinRAR.exe"; //WinRar安装路径!
                    unrar.StartInfo.Arguments = shellArguments; //隐藏rar本身的窗口
                    unrar.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    unrar.Start();
                    unrar.WaitForExit(); //等待解压完成
                    unrar.Close();
                }
                var dir = new DirectoryInfo(dirName);
                files.AddRange(dir.GetFiles());
            }
            return files;
        }

///// <summary>
        ///// 文件解压2(rar格式)使用SharpCompress组件 需.net 3.5以上才支持!
        ///// </summary>
        ///// <param name="rarFilePath"></param>
        ///// <returns></returns>
        //private static List<FileInfo> UnRarFile(string rarFilePath)
        //{
        //    var files = new List<FileInfo>();
        //    if (File.Exists(rarFilePath))
        //    {
        //        var fileInput = new FileInfo(rarFilePath);
        //        using (Stream stream = File.OpenRead(rarFilePath))
        //        {
        //            var reader = ReaderFactory.Open(stream);
        //            if (fileInput.Directory != null)
        //            {
        //                string dirName = Path.Combine(fileInput.Directory.FullName, fileInput.Name.Replace(fileInput.Extension, ""));

        //                if (!string.IsNullOrEmpty(dirName))
        //                {
        //                    if (!Directory.Exists(dirName))
        //                    {
        //                        Directory.CreateDirectory(dirName);
        //                    }
        //                }
        //                while (reader.MoveToNextEntry())
        //                {
        //                    if (!reader.Entry.IsDirectory)
        //                    {
        //                        reader.WriteEntryToDirectory(dirName, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
        //                        files.Add(new FileInfo(reader.Entry.FilePath));
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    return files;
        //}
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
linux常见压缩格式及deb安装包用法
ZIP格式评价:可能是目前使用的最多的文档压缩格式,跨平台。压缩率不高。压缩一个目录:\ziprarchive\_name.zipdirectory\_to\_compress解压缩:\unziparchive\_name.zipTAR格式评价:消耗cpu及时间少,仅仅是一个打包工具,并不负责压缩。
Stella981 Stella981
3年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Easter79 Easter79
3年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
9个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这