C# 文件压缩下载
来源:互联网 发布:卢瑟经济学-知乎 编辑:程序博客网 时间:2024/04/28 16:32
我们开发的过程中,有时用户要求下载的时候把文件进行压缩,以压缩包的形式下载到本地,方便保存和分类,以下是文件压缩的一个方法,以供参考
(注:System.IO.Packaging 需要引用WindowsBase.dll,才可以用)
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.IO.Packaging;
-
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("开始压缩");
- try
- {
- PackageFolder(@"E:\IMG", @"E:\压缩包.zip", false);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- Console.WriteLine("压缩完成");
- }
-
-
-
-
-
-
-
-
-
- public static Boolean PackageFolder(String folderName, String compressedFileName, Boolean overrideExisting)
- {
- if (folderName.EndsWith(@"\"))
- folderName = folderName.Remove(folderName.Length - 1);
- Boolean 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)
- {
-
- 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.Fast);
- using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
- {
- fileStream.CopyTo(packagePartDocument.GetStream());
- }
- }
- }
- result = true;
- }
- catch (Exception e)
- {
- throw new Exception("压缩文件夹错误: " + folderName, e);
- }
-
- return result;
- }
- }
- }