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

26 篇文章 0 订阅
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;
        //}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值