• 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);
                }
            }
        }
    }
  • 相关阅读:
    Vue、Node 全栈,结合使用获取数据
    Day3.18组件案例-发表评论功能
    Day3.17父组件向子组件传方法
    Day3.16父组件向子组件传值
    Day3.15组件切换动画
    Day3.14组件切换方式二
    把旧系统迁移到.Net Core 2.0 日记 (19) --UI转用adminLTE
    NopCommerce 更改发票字体
    本地可以发邮件,阿里云服务器发送邮件失败,25端口被禁用
    WIFI 万能钥匙万玉权:团队之中要有跨三界之外的“闲人” [转]
  • 原文地址:https://www.cnblogs.com/hellowzl/p/9071706.html
Copyright © 2020-2023  润新知