C#压缩解压文件并修改

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using ICSharpCode.SharpZipLib.Zip;  
  5.   
  6. namespace 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. }  
[csharp]   view plain  copy  print ?
  1. /// <summary>  
  2. ///     文件解压(Rar格式)  
  3. /// </summary>  
  4. /// <param name="rarFilePath"></param>  
  5. /// <returns></returns>  
  6. public static List<FileInfo> UnRarFile(string rarFilePath)  
  7. {  
  8.     var files = new List<FileInfo>();  
  9.     var fileInput = new FileInfo(rarFilePath);  
  10.     if (fileInput.Directory != null)  
  11.     {  
  12.         string dirName = Path.Combine(fileInput.Directory.FullName,  
  13.                                       fileInput.Name.Replace(fileInput.Extension, ""));  
  14.   
  15.         if (!string.IsNullOrEmpty(dirName))  
  16.         {  
  17.             if (!Directory.Exists(dirName))  
  18.             {  
  19.                 Directory.CreateDirectory(dirName);  
  20.             }  
  21.         }  
  22.         dirName = dirName.EndsWith("\\") ? dirName : dirName + "\\"; //最后这个斜杠不能少!  
  23.         string shellArguments = string.Format("x -o+ {0} {1}", rarFilePath, dirName);  
  24.         using (var unrar = new Process())  
  25.         {  
  26.             unrar.StartInfo.FileName = @"C:\Program Files\WinRAR\WinRAR.exe"//WinRar安装路径!  
  27.             unrar.StartInfo.Arguments = shellArguments; //隐藏rar本身的窗口  
  28.             unrar.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;  
  29.             unrar.Start();  
  30.             unrar.WaitForExit(); //等待解压完成  
  31.             unrar.Close();  
  32.         }  
  33.         var dir = new DirectoryInfo(dirName);  
  34.         files.AddRange(dir.GetFiles());  
  35.     }  
  36.     return files;  
  37. }  
[csharp]   view plain  copy  print ?
  1. / <summary>  
  2. / 文件解压2(rar格式)使用SharpCompress组件 需.net 3.5以上才支持!  
  3. / </summary>  
  4. / <param name="rarFilePath"></param>  
  5. / <returns></returns>  
  6. //private static List<FileInfo> UnRarFile(string rarFilePath)  
  7. //{  
  8. //    var files = new List<FileInfo>();  
  9. //    if (File.Exists(rarFilePath))  
  10. //    {  
  11. //        var fileInput = new FileInfo(rarFilePath);  
  12. //        using (Stream stream = File.OpenRead(rarFilePath))  
  13. //        {  
  14. //            var reader = ReaderFactory.Open(stream);  
  15. //            if (fileInput.Directory != null)  
  16. //            {  
  17. //                string dirName = Path.Combine(fileInput.Directory.FullName, fileInput.Name.Replace(fileInput.Extension, ""));  
  18.   
  19. //                if (!string.IsNullOrEmpty(dirName))  
  20. //                {  
  21. //                    if (!Directory.Exists(dirName))  
  22. //                    {  
  23. //                        Directory.CreateDirectory(dirName);  
  24. //                    }  
  25. //                }  
  26. //                while (reader.MoveToNextEntry())  
  27. //                {  
  28. //                    if (!reader.Entry.IsDirectory)  
  29. //                    {  
  30. //                        reader.WriteEntryToDirectory(dirName, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);  
  31. //                        files.Add(new FileInfo(reader.Entry.FilePath));  
  32. //                    }  
  33. //                }  
  34. //            }  
  35. //        }  
  36. //    }  
  37. //    return files;  
  38. //}
  39.         /// <summary>   
            /// 解压功能(解压压缩文件到指定目录)   
            /// </summary>   
            /// <param name="fileToUnZip">待解压的文件</param>   
            /// <param name="zipedFolder">指定解压目标目录</param>   
            /// <param name="password">密码</param>   
            /// <returns>解压结果</returns>   
            public static bool ChargeUnZip(string fileToUnZip, string zipedFolder, string password)
            {
                bool result = true;
                FileStream fs = null;
                ZipInputStream zipStream = null;
                ZipEntry ent = null;
                string fileName;

                if (!File.Exists(fileToUnZip))
                    return false;

                if (!Directory.Exists(zipedFolder))
                    Directory.CreateDirectory(zipedFolder);

                try
                {
                    zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
                    if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
                    while ((ent = zipStream.GetNextEntry()) != null)
                    {
                        if (!string.IsNullOrEmpty(ent.Name))
                        {
                            fileName = Path.Combine(zipedFolder, ent.Name);
                            fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi   
                            
                            if (fileName.EndsWith("\\"))
                            {
                                Directory.CreateDirectory(fileName);
                                continue;
                            }
                            fs= new FileStream(fileName, FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite);
                            int size = 2048;
                            byte[] data = new byte[size];

                                size = zipStream.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    fs.Write(data, 0, size);
                                    fs.Flush();
                                }
                                else
                                    break;
                        }
                    }
                }
                catch
                {
                    result = false;
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                        fs.Dispose();
                    }
                    if (zipStream != null)
                    {
                        zipStream.Close();
                        zipStream.Dispose();
                    }
                    if (ent != null)
                    {
                        ent = null;
                    }
                    fs.Flush();
                    fs.Close();

                    GC.Collect();
                    GC.Collect(1);
                }
                return result;
            }

            /// <summary>   
            /// 解压功能(解压压缩文件到指定目录)   
            /// </summary>   
            /// <param name="fileToUnZip">待解压的文件</param>   
            /// <param name="zipedFolder">指定解压目标目录</param>   
            /// <returns>解压结果</returns>   
            public static bool ChargeUnZip1(string fileToUnZip, string zipedFolder)
            {
                bool result = ChargeUnZip(fileToUnZip, zipedFolder, null);
                return result;
            } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值