您的位置:首页 > 编程语言 > C#

C#压缩解压文件并修改

2017-07-06 17:59 621 查看
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;  

        }  

    }  

}  

[csharp] view
plain copy print?

/// <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;  

}  

[csharp] view
plain copy print?

///// <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;  

//}

        /// <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;

        } 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: