C#压缩文件夹坑~
开始从网上找了个压缩的示例 我去坑的不要不要的 没办法重新找 都是复制来复制去 没啥意思
前提:ICSharpCode.SharpZipLib.dll引用
创建一个类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
public
class
ZipClass
{
/// <summary>
/// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略)
/// </summary>
/// <param name="dirPath">被压缩的文件夹夹路径</param>
/// <param name="zipFilePath">生成压缩文件的路径</param>
/// <returns>是否压缩成功</returns>
public
static
bool
ZipFiles(
string
dirPath,
string
zipFilePath )
{
try
{
string
[] filenames = Directory.GetFiles(dirPath);
using
(ZipOutputStream s =
new
ZipOutputStream(File.Create(zipFilePath)))
{
s.SetLevel(9);
//0-9 值越大压缩率越高
byte
[] buffer =
new
byte
[4096];
foreach
(
string
file
in
filenames)
{
ZipEntry entry =
new
ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using
(FileStream fs = File.OpenRead(file))
{
int
sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
}
while
(sourceBytes > 0);
}
}
s.Finish();
s.Close();
}
}
catch
(Exception ex)
{
return
false
;
}
return
true
;
}
}
|