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

相关推荐
用户36674625267417 分钟前
接口文档汇总 - 2.设备状态管理
c#
用户36674625267425 分钟前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang20 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf4 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530144 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools5 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的5 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21886 天前
.NET 本地Db数据库-技术方案选型
windows·c#
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
lindexi6 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice