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

1using System; 2using System.Collections.Generic; 3using System.IO; 4using ICSharpCode.SharpZipLib.Zip; 5 6namespace TestConsole 7{ 8    internal class Program 9    { 10        private static void Main() 11        { 12            //CreateZipFile(@"d:\", @"d:\a.zip"); 13            UnZipFile(@"E:\我的桌面.zip");  14            Console.Read(); 15        } 16 17        /// <summary> 18        ///     压缩文件为zip包 19        /// </summary> 20        /// <param name="filesPath"></param> 21        /// <param name="zipFilePath"></param> 22        private static bool CreateZipFile(string filesPath, string zipFilePath) 23        { 24            if (!Directory.Exists(filesPath)) 25            { 26                return false; 27            } 28 29            try 30            { 31                string[] filenames = Directory.GetFiles(filesPath); 32                using (var s = new ZipOutputStream(File.Create(zipFilePath))) 33                { 34                    s.SetLevel(9); // 压缩级别 0-9 35                    //s.Password = "123"; //Zip压缩文件密码 36                    var buffer = new byte[4096]; //缓冲区大小 37                    foreach (string file in filenames) 38                    { 39                        var entry = new ZipEntry(Path.GetFileName(file)); 40                        entry.DateTime = DateTime.Now; 41                        s.PutNextEntry(entry); 42                        using (FileStream fs = File.OpenRead(file)) 43                        { 44                            int sourceBytes; 45                            do 46                            { 47                                sourceBytes = fs.Read(buffer, 0, buffer.Length); 48                                s.Write(buffer, 0, sourceBytes); 49                            } while (sourceBytes > 0); 50                        } 51                    } 52                    s.Finish(); 53                    s.Close(); 54                } 55                return true; 56            } 57            catch (Exception ex) 58            { 59                Console.WriteLine("Exception during processing {0}", ex); 60            } 61            return false; 62        } 63 64        /// <summary> 65        ///     文件解压(zip格式) 66        /// </summary> 67        /// <param name="zipFilePath"></param> 68        /// <returns></returns> 69        private static List<FileInfo> UnZipFile(string zipFilePath) 70        { 71            var files = new List<FileInfo>(); 72            var zipFile = new FileInfo(zipFilePath); 73            if (!File.Exists(zipFilePath)) 74            { 75                return files; 76            } 77            using (var zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath))) 78            { 79                ZipEntry theEntry; 80                while ((theEntry = zipInputStream.GetNextEntry()) != null) 81                { 82                    if (zipFilePath != null) 83                    { 84                        string dir = Path.GetDirectoryName(zipFilePath); 85                        if (dir != null) 86                        { 87                            string dirName = Path.Combine(dir, zipFile.Name.Replace(zipFile.Extension, "")); 88                            string fileName = Path.GetFileName(theEntry.Name); 89 90                            if (!string.IsNullOrEmpty(dirName)) 91                            { 92                                if (!Directory.Exists(dirName)) 93                                { 94                                    Directory.CreateDirectory(dirName); 95                                } 96                            } 97                            if (!string.IsNullOrEmpty(fileName)) 98                            { 99                                string filePath = Path.Combine(dirName, theEntry.Name); 100                                using (FileStream streamWriter = File.Create(filePath)) 101                                { 102                                    var data = new byte[2048]; 103                                    while (true) 104                                    { 105                                        int size = zipInputStream.Read(data, 0, data.Length); 106                                        if (size > 0) 107                                        { 108                                            streamWriter.Write(data, 0, size); 109                                        } 110                                        else 111                                        { 112                                            break; 113                                        } 114                                    } 115                                } 116                                files.Add(new FileInfo(filePath)); 117                            } 118                        } 119                    } 120                } 121            } 122            return files; 123        } 124    } 125} 126 127/// <summary> 128        ///     文件解压(Rar格式) 129        /// </summary> 130        /// <param name="rarFilePath"></param> 131        /// <returns></returns> 132        public static List<FileInfo> UnRarFile(string rarFilePath) 133        { 134            var files = new List<FileInfo>(); 135            var fileInput = new FileInfo(rarFilePath); 136            if (fileInput.Directory != null) 137            { 138                string dirName = Path.Combine(fileInput.Directory.FullName, 139                                              fileInput.Name.Replace(fileInput.Extension, "")); 140 141                if (!string.IsNullOrEmpty(dirName)) 142                { 143                    if (!Directory.Exists(dirName)) 144                    { 145                        Directory.CreateDirectory(dirName); 146                    } 147                } 148                dirName = dirName.EndsWith("\\") ? dirName : dirName + "\\"; //最后这个斜杠不能少! 149                string shellArguments = string.Format("x -o+ {0} {1}", rarFilePath, dirName); 150                using (var unrar = new Process()) 151                { 152                    unrar.StartInfo.FileName = @"C:\Program Files\WinRAR\WinRAR.exe"; //WinRar安装路径! 153                    unrar.StartInfo.Arguments = shellArguments; //隐藏rar本身的窗口 154                    unrar.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 155                    unrar.Start(); 156                    unrar.WaitForExit(); //等待解压完成 157                    unrar.Close(); 158                } 159                var dir = new DirectoryInfo(dirName); 160                files.AddRange(dir.GetFiles()); 161            } 162            return files; 163        } 164 165///// <summary> 166        ///// 文件解压2(rar格式)使用SharpCompress组件 需.net 3.5以上才支持! 167        ///// </summary> 168        ///// <param name="rarFilePath"></param> 169        ///// <returns></returns> 170        //private static List<FileInfo> UnRarFile(string rarFilePath) 171        //{ 172        //    var files = new List<FileInfo>(); 173        //    if (File.Exists(rarFilePath)) 174        //    { 175        //        var fileInput = new FileInfo(rarFilePath); 176        //        using (Stream stream = File.OpenRead(rarFilePath)) 177        //        { 178        //            var reader = ReaderFactory.Open(stream); 179        //            if (fileInput.Directory != null) 180        //            { 181        //                string dirName = Path.Combine(fileInput.Directory.FullName, fileInput.Name.Replace(fileInput.Extension, "")); 182 183        //                if (!string.IsNullOrEmpty(dirName)) 184        //                { 185        //                    if (!Directory.Exists(dirName)) 186        //                    { 187        //                        Directory.CreateDirectory(dirName); 188        //                    } 189        //                } 190        //                while (reader.MoveToNextEntry()) 191        //                { 192        //                    if (!reader.Entry.IsDirectory) 193        //                    { 194        //                        reader.WriteEntryToDirectory(dirName, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); 195        //                        files.Add(new FileInfo(reader.Entry.FilePath)); 196        //                    } 197        //                } 198        //            } 199        //        } 200        //    } 201        //    return files; 202        //}
点赞
收藏

评论区

加载中...

相关推荐

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

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

SpringBoot整合Redis乱码原因及解决方案

问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa

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