zoukankan      html  css  js  c++  java
  • C# 文件压缩方法

    using System;
    using System.IO;
    using System.IO.Packaging;
    
    namespace Utility
    {
        public class ZipHelper
        {
            ///<summary>
            /// Add a folder along with its subfolders to a Package
            /// </summary>
            /// <param name="folderName">The folder to add</param>
            /// <param name="compressedFileName">The package to create</param>
            /// <param name="overrideExisting">Override exsisitng files</param>
            /// <returns></returns>
            public static bool PackageFolder(string folderName, string compressedFileName, bool overrideExisting)
            {
                if (folderName.EndsWith(@""))
                    folderName = folderName.Remove(folderName.Length - 1);
                bool result = false;
                if (!Directory.Exists(folderName))
                {
                    return result;
                }
    
                if (!overrideExisting && File.Exists(compressedFileName))
                {
                    return result;
                }
                try
                {
                    using (Package package = Package.Open(compressedFileName, FileMode.Create))
                    {
                        var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
                        foreach (string fileName in fileList)
                        {
    
                            //The path in the package is all of the subfolders after folderName
                            string pathInPackage;
                            pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName);
    
                            Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
                            PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
                            using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                            {
                                fileStream.CopyTo(packagePartDocument.GetStream());
                            }
                        }
                    }
                    result = true;
                }
                catch (Exception e)
                {
                    throw new Exception("Error zipping folder " + folderName, e);
                }
    
                return result;
            }
        }
    }
    using ICSharpCode.SharpZipLib.Checksums;
    using ICSharpCode.SharpZipLib.Zip;
    using System;
    using System.IO;
    
    namespace Utility
    {
        /// <summary>
        /// 需要引用NuGet包:ICSharpCode.SharpZipLib
        /// </summary>
        public class ZipNewHelper
        {
            public void ZipFile(string strFile, string strZip)
            {
                if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
                    strFile += Path.DirectorySeparatorChar;
                ZipOutputStream s = new ZipOutputStream(File.Create(strZip));
                s.SetLevel(6); // 0 - store only to 9 - means best compression
                zip(strFile, s, strFile);
                s.Finish();
                s.Close();
            }
    
    
            private void zip(string strFile, ZipOutputStream s, string staticFile)
            {
                if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) strFile += Path.DirectorySeparatorChar;
                Crc32 crc = new Crc32();
                string[] filenames = Directory.GetFileSystemEntries(strFile);
                foreach (string file in filenames)
                {
    
                    if (Directory.Exists(file))
                    {
                        zip(file, s, staticFile);
                    }
    
                    else // 否则直接压缩文件
                    {
                        //打开压缩文件
                        FileStream fs = File.OpenRead(file);
    
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        string tempfile = file.Substring(staticFile.LastIndexOf("\") + 1);
                        ZipEntry entry = new ZipEntry(tempfile);
    
                        entry.DateTime = DateTime.Now;
                        entry.Size = fs.Length;
                        fs.Close();
                        crc.Reset();
                        crc.Update(buffer);
                        entry.Crc = crc.Value;
                        s.PutNextEntry(entry);
    
                        s.Write(buffer, 0, buffer.Length);
                    }
                }
            }
        }
    }
    using System;
    using System.IO;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string parentDir = @"E:92-收藏文档C#";
                DeleteFiles(parentDir);
            }
    
            public static void DeleteFiles(string str)
            {
                DirectoryInfo fatherFolder = new DirectoryInfo(str);
                //删除子文件夹
                //DirectoryInfo[] childFolders = fatherFolder.GetDirectories();
                //foreach (DirectoryInfo dir in childFolders)
                //{
                //    try
                //    {
                //        string dirName = dir.Name;
                //        if (dirName.Contains("obj"))
                //        {
                //            Directory.Delete(dir.FullName, true);
                //        }
                //    }
                //    catch (Exception ex)
                //    { }
                //}
    
                //删除当前文件夹内文件
                FileInfo[] files = fatherFolder.GetFiles();
                foreach (FileInfo file in files)
                {
                    //string fileName = file.FullName.Substring((file.FullName.LastIndexOf("\") + 1), file.FullName.Length - file.FullName.LastIndexOf("\") - 1);
                    string fileName = file.Name;
                    try
                    {
                        if (fileName.Contains("cs"))
                        {
                            //File.Delete(file.FullName);
                            string path = file.FullName;
                            //Path.ChangeExtension(path, "txt");
                            File.Move(path, Path.ChangeExtension(path, "txt"));
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
    
    
                //递归删除子文件夹内文件
                foreach (DirectoryInfo childFolder in fatherFolder.GetDirectories())
                {
                    DeleteFiles(childFolder.FullName);
                }
            }
        }
    }
  • 相关阅读:
    C#操作REDIS例子
    A C# Framework for Interprocess Synchronization and Communication
    UTF8 GBK UTF8 GB2312 之间的区别和关系
    开源项目选型问题
    Mysql命令大全——入门经典
    RAM, SDRAM ,ROM, NAND FLASH, NOR FLASH 详解(引用)
    zabbix邮件报警通过脚本来发送邮件
    centos启动提示unexpected inconsistency RUN fsck MANUALLY
    rm 或者ls 报Argument list too long
    初遇Citymaker (六)
  • 原文地址:https://www.cnblogs.com/hellowzl/p/9071706.html
Copyright © 2011-2022 走看看