c# 动态操作 zip\rar 文件,压缩解压组件使用

c# 动态操作 zip\rar 文件,压缩解压组件使用


c# 动态操作一个压缩文件,可以动态完成以下操作
1.创建一个 zip
2.向 zip 中附加文件
3.更新 zip 中指定文件
4.删除 zip 中指定文件
5.解压缩 zip 

6.在zip中提取一个文件


using System;
using System.IO;
using Ionic.Zip;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;

namespace TestIonicZip
{
    [TestClass]
    public class TestZip
    {
        /// 
        /// 创建一个 zip
        /// 
        [TestMethod]
        public void CreateZip()
        {
            var baseDir = Path.GetFullPath(@"..\..\zips");
            var zipPath = Path.Combine(baseDir,
                string.Format("{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss")));

            var imgDir = Path.GetFullPath(@"..\..\img");
            var files = Directory.GetFiles(imgDir);

            using (ZipFile zip = new ZipFile())
            {
                String[] filenames = System.IO.Directory.GetFiles(imgDir);

                foreach (String filename in filenames)
                {
                    ZipEntry e = zip.AddFile(filename,"");
                    e.Comment = "Added by Cheeso's CreateZip utility.";
                }

                zip.Comment = String.Format("This zip archive was created by the CreateZip example application on machine '{0}'",
                    System.Net.Dns.GetHostName());

                zip.Save(zipPath);
            }
        }
        /// 
        /// 向 zip 中附加文件
        /// 
        [TestMethod]
        public void AppendToZip()
        {
            var baseDir = Path.GetFullPath(@"..\..\zips");
            var zipPath = Path.Combine(baseDir,
                string.Format("{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss")));
            var zipFix = Path.Combine(baseDir,"20151202194926.zip");

            var imgDir = Path.GetFullPath(@"..\..\img");
            var files = Directory.GetFiles(imgDir);

            using (ZipFile zip = new ZipFile(zipFix))
            {
                String[] filenames = System.IO.Directory.GetFiles(imgDir);

                foreach (String filename in filenames)
                {
                    ZipEntry e = zip.AddFile(filename, "aa");
                    e.Comment = "Added by Cheeso's CreateZip utility.";
                }

                zip.Comment = String.Format("This zip archive was created by the CreateZip example application on machine '{0}'",
                    System.Net.Dns.GetHostName());

                zip.Save();
            }
        }
        /// 
        /// 更新 zip 中指定文件
        /// 
        [TestMethod]
        public void UpdateZip()
        {
            var baseDir = Path.GetFullPath(@"..\..\zips");
            var zipPath = Path.Combine(baseDir,
                string.Format("{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss")));
            var zipFix = Path.Combine(baseDir, "20151202194926.zip");

            var imgDir = Path.GetFullPath(@"..\..\img");
            var files = Directory.GetFiles(imgDir);

            var bCount = 0;
            var aCount = 0;
            using (ZipFile zip = new ZipFile(zipFix))
            {
                // note: this does not recurse directories! 
                String[] filenames = System.IO.Directory.GetFiles(imgDir);

                bCount = zip.Count;
                //删除一个文件
                var fileName = "003.jpg";
                var sourceFile = Path.Combine(imgDir, "004.jpg");
                if (zip.ContainsEntry(fileName))
                {
                    var stream = File.OpenRead(sourceFile);
                    var z = zip.UpdateEntry(fileName, stream);
                    z.Comment = DateTime.Now.ToString();
                }
                zip.Comment = String.Format("This zip archive was created by the CreateZip example application on machine '{0}'",
                    System.Net.Dns.GetHostName());

                zip.Save();

                aCount = zip.Count;
            }
        }
        /// 
        /// 删除 zip 中指定文件
        /// 
        [TestMethod]
        public void DeleteFromZip()
        {
            var baseDir = Path.GetFullPath(@"..\..\zips");
            var zipPath = Path.Combine(baseDir,
                string.Format("{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss")));
            var zipFix = Path.Combine(baseDir, "20151202194926.zip");

            var imgDir = Path.GetFullPath(@"..\..\img");
            var files = Directory.GetFiles(imgDir);

            var bCount = 0;
            var aCount = 0;
            using (ZipFile zip = new ZipFile(zipFix))
            {
                // note: this does not recurse directories! 
                String[] filenames = System.IO.Directory.GetFiles(imgDir);

                bCount = zip.Count;
                //删除一个文件
                if(zip.ContainsEntry("002.jpg"))
                    zip.RemoveEntry("002.jpg");
                //删除一个文件,目录
                var removeFile = "/aa/002.jpg";
                if (zip.ContainsEntry(removeFile))
                    zip.RemoveEntry(removeFile);

                zip.Comment = String.Format("This zip archive was created by the CreateZip example application on machine '{0}'",
                    System.Net.Dns.GetHostName());

                zip.Save();

                aCount = zip.Count;
            }
            Assert.IsTrue(bCount-1==aCount);
        }

        /// 
        /// 解压缩 zip 
        /// 
        [TestMethod]
        public void ExtractZip()
        {
            var baseDir = Path.GetFullPath(@"..\..\zips");
            var zipPath = Path.Combine(baseDir,
                string.Format("{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss")));
            var zipFix = Path.Combine(baseDir, "20151202194926.zip");

            var imgDir = Path.GetFullPath(@"..\..\img");
            var files = Directory.GetFiles(imgDir);

            var bCount = 0;
            var aCount = 0;
            
            using (ZipFile zip = new ZipFile(zipFix))
            {
                var dir = Path.Combine(baseDir, "Extract");
                zip.ExtractAll(dir);
            }
        }

        /// 
        /// 提取一个 文件
        /// 
        [TestMethod]
        public void ExtractZipByName()
        {
            var baseDir = Path.GetFullPath(@"..\..\zips");
            var zipPath = Path.Combine(baseDir,
                string.Format("{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss")));
            var zipFix = Path.Combine(baseDir, "20151202194926.zip");

            var imgDir = Path.GetFullPath(@"..\..\img");
            var files = Directory.GetFiles(imgDir);

            var bCount = 0;
            var aCount = 0;
            byte[] content = null;
            //转换stream为byte[]
            Func toByteArray = (stream) =>
            {
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始 
                stream.Seek(0, SeekOrigin.Begin);
                return bytes;
            };
            var fileName = "004.jpg";
            using (ZipFile zip = new ZipFile(zipFix))
            {
                if (zip.ContainsEntry(fileName))
                {
                    //在跟目录找
                    var entrys = zip.SelectEntries(fileName,"");
                    var entry = entrys.FirstOrDefault();
                    //将文件解压到内存流
                    using (var stream = new MemoryStream())
                    {
                        entry.Extract(stream);
                        stream.Seek(0, SeekOrigin.Begin);
                        content = toByteArray(stream);
                    }
                    
                    //在aa目录找
                    var entrys1 = zip.SelectEntries(fileName, "aa");
                    var entry1 = entrys.FirstOrDefault();
                }
            }
            //创建文件
            var extractImg = Path.Combine(baseDir, fileName);
            File.WriteAllBytes(extractImg, content);
            Assert.IsTrue(File.Exists(extractImg));
        }
    }
}


你可能感兴趣的:(技术资料)