C#压缩单个文件

1、压缩方法

/// <summary>

/// 压缩

/// </summary>

/// <param name="source">源目录</param>

/// <param name="s">ZipOutputStream对象</param>

public static void Compress(string source, ZipOutputStream s)

{

string[] filenames = Directory.GetFiles(source);

foreach (string file in filenames)

{

using (FileStream fs = File.OpenRead(file))

{

byte[] buffer = new byte[4 * 1024];

ZipEntry entry = new ZipEntry(Path.GetFileName(file));

entry.DateTime = DateTime.Now;

s.PutNextEntry(entry);

int sourceBytes;

do

{

sourceBytes = fs.Read(buffer, 0, buffer.Length);

s.Write(buffer, 0, sourceBytes);

} while (sourceBytes > 0);

}

}

}

2、压缩单个文件

/// <summary>

/// 压缩单个文件

///</summary>

/// <param name="fileToZip">要进行压缩的文件名</param>

/// <param name="zipedFile">压缩后生成的压缩文件名</param>

public static void ZipFile(string fileToZip, string zipedFile)

{

try

{

Directory.CreateDirectory(Path.GetDirectoryName(zipedFile));

using (ZipOutputStream s = new ZipOutputStream(File.Create(zipedFile)))

{

s.SetLevel(6);

Compress(fileToZip, s);

s.Finish();

s.Close();

}

Console.Read();

}

catch (Exception ex)

{

throw new System.Exception(ex.Message);

}

}

3、调用

ZipFile("C\\档案\\测试1", C\\档案\\测试1 + ".zip");

相关推荐
Coding茶水间6 小时前
基于深度学习的花朵识别系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
开发语言·人工智能·深度学习·yolo·目标检测·机器学习
moxiaoran57537 小时前
Go语言的文件操作
开发语言·后端·golang
我命由我123457 小时前
Android 开发问题:Duplicate class android.support.v4.app.INotificationSideChannel...
android·java·开发语言·java-ee·android studio·android-studio·android runtime
kylezhao20197 小时前
C#中开放 - 封闭原则(**Open-Closed Principle,OCP**)
服务器·c#·开闭原则
小白学大数据7 小时前
Python 进阶爬虫:解析知识星球 API
开发语言·爬虫·python
赴前尘7 小时前
记一次golang进程执行卡住的问题排查
开发语言·后端·golang
whale fall7 小时前
如何在同一台电脑里安装32 位 Python 和 64 位 Python
开发语言·笔记·python·学习
.清和.7 小时前
【js】Javascript事件循环机制
开发语言·javascript·ecmascript
瑞雪兆丰年兮7 小时前
[从0开始学Java|第十一天]ArrayList
java·开发语言
黄筱筱筱筱筱筱筱7 小时前
第三次Python练习题
开发语言·python