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

相关推荐
星星法术嗲人10 分钟前
【Java】—— 集合框架:Collections工具类的使用
java·开发语言
黑不溜秋的23 分钟前
C++ 语言特性29 - 协程介绍
开发语言·c++
一丝晨光28 分钟前
C++、Ruby和JavaScript
java·开发语言·javascript·c++·python·c·ruby
天上掉下来个程小白31 分钟前
Stream流的中间方法
java·开发语言·windows
xujinwei_gingko42 分钟前
JAVA基础面试题汇总(持续更新)
java·开发语言
sp_wxf1 小时前
Lambda表达式
开发语言·python
Fairy_sevenseven1 小时前
【二十八】【QT开发应用】模拟WPS Tab
开发语言·qt·wps
蜡笔小新星1 小时前
Python Kivy库学习路线
开发语言·网络·经验分享·python·学习
凯子坚持 c1 小时前
C语言复习概要(三)
c语言·开发语言
无限大.1 小时前
c语言200例 067
java·c语言·开发语言