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

简介:
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;
        //}



目录
相关文章
|
5月前
|
Java
Java实现zip文件压缩:单个文件、文件夹以及文件和文件夹的压缩
Java实现zip文件压缩:单个文件、文件夹以及文件和文件夹的压缩
|
11月前
|
Linux
Linux文件的压缩和解压(各种格式文件类型介绍)
Linux文件的压缩和解压(各种格式文件类型介绍)
|
Java 程序员
批量压缩16万个文件夹为压缩包(.zip格式)
🍅程序员小王的博客:程序员小王的博客 🍅 欢迎点赞 👍 收藏 ⭐留言 📝 🍅 如有编辑错误联系作者,如果有比较好的文章欢迎分享给我,我会取其精华去其糟粕 🍅java自学的学习路线:java自学的学习路线
198 0
批量压缩16万个文件夹为压缩包(.zip格式)
7zip压缩zip格式时文件名支持中文的设置
7zip压缩zip格式时文件名支持中文的设置
82 0
7zip压缩zip格式时文件名支持中文的设置
|
存储 Linux Windows
4.3 Linux压缩文件或目录为.zip格式(zip命令)
本节要讲的 zip 命令,类似于 Windows 系统中的 winzip 压缩程序,其基本格式如下:
153 0
4.3 Linux压缩文件或目录为.zip格式(zip命令)
|
Linux
4.5 Linux压缩文件或目录中文件为.gz格式(gzip命令)
gzip 是 Linux 系统中经常用来对文件进行压缩和解压缩的命令,通过此命令压缩得到的新文件,其扩展名通常标记为“.gz”。
188 0
4.5 Linux压缩文件或目录中文件为.gz格式(gzip命令)
|
Linux
zip和unzip区分
zip和unzip区分
156 0
最新!压缩为rar格式方法,目前只能用:WinRAR压缩工具-rar压缩格式的版权所有者。
最新!压缩为rar格式方法,目前只能用:WinRAR压缩工具-rar压缩格式的版权所有者。
202 0
最新!压缩为rar格式方法,目前只能用:WinRAR压缩工具-rar压缩格式的版权所有者。
|
Python
Python 技术篇-用zipfile库进行zip文件的压缩与解压实例演示,python压缩本地文件夹为zip文件并保留目录结构
Python 技术篇-用zipfile库进行zip文件的压缩与解压实例演示,python压缩本地文件夹为zip文件并保留目录结构
298 0
Python 技术篇-用zipfile库进行zip文件的压缩与解压实例演示,python压缩本地文件夹为zip文件并保留目录结构
|
Python
python-批量把文件和文件夹同时压缩成ZIP文件
1.通过某种方式获得一个文件(文件夹)列表作为一个list(例如wxpython的wx.FileDialog方法,在下面的代码中我们跳过文件夹列表的获取方法)。 2.选择一个压缩文件的输出目录和压缩文件的输出名字(下面代码中选择输出默认路径为程序根目录) 3.把文件list里的文件,先统一放在一个临时文件夹里,然后把该临时文件夹压缩成ZIP文件,最后删掉临时文件夹
258 0