C#文件压缩成.Zip
2024-09-07 14:56:03
使用的三方类库ICSharpCode.SharpZipLib.dll
方法如下:
/// <summary>
/// 压缩文件为zip格式
/// </summary>
/// <param name="filepath">文件地址</param>
/// <param name="targetPath">目标路径</param>
static bool CompressFiles(string filePath, string targetPath)
{
try
{
using (ZipOutputStream zipstream = new ZipOutputStream(File.Create(targetPath)))
{
zipstream.SetLevel(); // 压缩级别 0-9
byte[] buffer = new byte[]; //缓冲区大小
ZipEntry entry = new ZipEntry(Path.GetFileName(filePath));
entry.DateTime = DateTime.Now;
zipstream.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(filePath))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
zipstream.Write(buffer, , sourceBytes);
}
while (sourceBytes > );
}
zipstream.Finish();
zipstream.Close();
return true;
}
}
catch (Exception ex)
{
return false;
}
}
压缩文件夹
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="strFile"></param>
/// <param name="strZip"></param>
/// <returns></returns>
public static bool ZipFile(string strFile, string strZip)
{
try
{
if (strFile[strFile.Length - ] != Path.DirectorySeparatorChar)
{
strFile += Path.DirectorySeparatorChar;
}
ZipOutputStream outstream = new ZipOutputStream(File.Create(strZip));
outstream.SetLevel();
ZipCompress(strFile, outstream, strFile);
outstream.Finish();
outstream.Close();
return true;
}
catch (Exception)
{
return false;
}
} public static void ZipCompress(string strFile, ZipOutputStream outstream, string staticFile)
{
if (strFile[strFile.Length - ] != Path.DirectorySeparatorChar)
{
strFile += Path.DirectorySeparatorChar;
}
Crc32 crc = new Crc32();
//获取指定目录下所有文件和子目录文件名称
string[] filenames = Directory.GetFileSystemEntries(strFile);
//遍历文件
foreach (string file in filenames)
{
if (Directory.Exists(file))
{
ZipCompress(file, outstream, staticFile);
}
//否则,直接压缩文件
else
{
//打开文件
FileStream fs = File.OpenRead(file);
//定义缓存区对象
byte[] buffer = new byte[fs.Length];
//通过字符流,读取文件
fs.Read(buffer, , buffer.Length);
//得到目录下的文件(比如:D:\Debug1\test),test
string tempfile = file.Substring(staticFile.LastIndexOf("\\") + );
ZipEntry entry = new ZipEntry(tempfile);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
outstream.PutNextEntry(entry);
//写文件
outstream.Write(buffer, , buffer.Length);
}
}
}
最新文章
- C# Invoke或者BeginInvoke的使用
- webpack-vue搭建,部署到后端
- matlab生成HEX文件-任意信号 大于64K长度
- MySQL rename database如何做?
- javascript的变态位运算
- 使用 Feedly RSS阅读器订阅技术大牛的博客
- C# - 接口,继承
- Excel技巧收录
- BZOJ 1072 排列
- Common Git command and mean (Windows)
- 关于echarts 报错 初始化对象未定义
- Balanced Sequence HDU - 6299(杭电多校1 B)
- golang gui library 库
- springboot1 缓存前端
- 【python学习-5】面向对象的python
- [C语言]声明解析器cdecl修改版
- jmeter结果分析(图形报表和聚合报告)
- linux编程实践:实现pwd命令
- SQLAlchemy技术文档(中文版)-上
- WarTransportation TopCoder - 8404