c# 实现zip格式文件的压缩和解压缩

1.  利用SharpZipLib进行zip的压缩和解压缩,需要导入ICSharpCode.SharpZipLib.dll。网上有 可以去下载

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
using System.IO;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            UpZipFile(@"G:\Users\windren\Desktop\BBBW_2012-07-09_AA-PC.SPR.zip");
            Console.ReadLine();            
        }

        private static void CreateZipFile(string filesPath, string zipFilePath)
        {

            if (!Directory.Exists(filesPath))
            {
                Console.WriteLine("Cannot find directory '{0}'", filesPath);
                return;
            }

            try
            {
                string[] filenames = Directory.GetFiles(filesPath);
                using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
                {
                    s.SetLevel(9); // 压缩级别 0-9
                    //s.Password = "123"; //Zip压缩文件密码
                    byte[] buffer = new byte[4096]; //缓冲区大小
                    foreach (string file in filenames)
                    {
                        ZipEntry 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();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception during processing {0}", ex);
            }
        }

        private static void UpZipFile(string filepath)
        {
            if (!File.Exists(filepath))
            {
                Console.WriteLine("Cannot find file '{0}'", filepath);
                return;
            }

            using (ZipInputStream sm = new ZipInputStream(File.OpenRead(filepath)))
            {
                ZipEntry entry;
                while ((entry = sm.GetNextEntry()) != null)
                {
                    Console.WriteLine(entry.Name);

                    string directoryName = Path.GetDirectoryName(entry.Name);
                    string fileName = Path.GetFileName(entry.Name);

                    if (directoryName.Length > 0)
                        Directory.CreateDirectory(directoryName);

                    if (!String.IsNullOrEmpty(fileName))
                    {
                        using (FileStream streamWriter = File.Create(entry.Name))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = sm.Read(data, 0, data.Length);
                                if (size > 0)
                                    streamWriter.Write(data, 0, size);
                                else
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }
}


2.  除了利用第三方的开源库之外,我们也可以利用.net自带的类进行操作。

c# 实现zip格式文件的压缩和解压缩_第1张图片

添加WindowsBase引用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Packaging;

namespace MEditor
{
    class ZipManager
    {
        public string SourceFolderPath { get; set; }

        public ZipManager(string sourceFolderPath)
        {
            SourceFolderPath = sourceFolderPath;
        }

        public void ZipFolder(string zipFilePath)
        {
            using (Package package = Package.Open(zipFilePath, System.IO.FileMode.Create))
            {
                DirectoryInfo di = new DirectoryInfo(SourceFolderPath);
                ZipDirectory(di, package);
            }
        }

        private void ZipDirectory(DirectoryInfo di, Package package)
        {
            foreach (FileInfo fi in di.GetFiles())
            {
                string relativePath = fi.FullName.Replace(SourceFolderPath, string.Empty);
                relativePath = relativePath.Replace("\\", "/");
                PackagePart part = package.CreatePart(new Uri(relativePath, UriKind.Relative),
                    System.Net.Mime.MediaTypeNames.Application.Zip);
                using (FileStream fs = fi.OpenRead())
                {
                    CopyStream(fs, part.GetStream());
                }

            }

            foreach (DirectoryInfo subDi in di.GetDirectories())
            {
                ZipDirectory(subDi, package);
            }
        }

        private void CopyStream(Stream source, Stream target)
        {
            const int bufSize = 0x1000;
            byte[] buf = new byte[bufSize];
            int bytesRead = 0;
            while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
            {
                target.Write(buf, 0, bytesRead);
            }
        }
    }
}

你可能感兴趣的:(c# 实现zip格式文件的压缩和解压缩)