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");

相关推荐
升鲜宝供应链及收银系统源代码服务5 分钟前
OMS 订单模块重构正式文档(一)---升鲜宝生鲜配送供应链管理系统
java·开发语言·重构·生鲜配送源代码·生鲜供应链源代码
qq_12084093711 小时前
Three.js 工程向:GLTFLoader 管线、Draco/KTX2 与资源管理
开发语言·javascript·ecmascript
下地种菜小叶1 小时前
定时任务系统怎么设计?一次讲清任务注册、分布式调度、幂等执行与失败补偿
java·开发语言·数据库·oracle·rabbitmq
csbysj20201 小时前
业务代表模式
开发语言
sghuter1 小时前
AI重塑工程师:未来核心能力全景图
开发语言·perl·composer·symfony
浪客川1 小时前
【百例RUST - 013】泛型
开发语言·后端·rust
iiiiyu2 小时前
常用API(SimpleDateFormat类 & Calendar类 & JDK8日期 时间 日期时间 & JDK8日期(时区) )
java·大数据·开发语言·数据结构·编程语言
故事和你912 小时前
洛谷-数据结构1-4-图的基本应用2
开发语言·数据结构·算法·深度优先·动态规划·图论
qq_12084093712 小时前
Three.js 工程向:Clock、deltaTime 与固定步长主循环
开发语言·javascript·ecmascript
小菜同学爱学习2 小时前
夯实基础!MySQL数据类型进阶、约束详解与报错排查
开发语言·数据库·sql·mysql