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
50
51
52
53
54
55
56
57
58
59
60
61
62
|
// SharpZipLibrary samples
// Copyright (c) 2007, AlphaSierraPapa
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// - Neither the name of the SharpDevelop team nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using
System;
using
System.Text;
using
System.Collections;
using
System.IO;
using
ICSharpCode.SharpZipLib.Zip;
class
MainClass
{
static
public
void
Main(
string
[] args)
{
if
( args.Length < 1 ) {
Console.WriteLine(
"Usage: ZipList file"
);
return
;
}
if
( !File.Exists(args[0]) ) {
Console.WriteLine(
"Cannot find file"
);
return
;
}
using
(ZipFile zFile =
new
ZipFile(args[0])) {
Console.WriteLine(
"Listing of : "
+ zFile.Name);
Console.WriteLine(
""
);
Console.WriteLine(
"Raw Size Size Date Time Name"
);
Console.WriteLine(
"-------- -------- -------- ------ ---------"
);
foreach
(ZipEntry e
in
zFile) {
DateTime d = e.DateTime;
Console.WriteLine(
"{0, -10}{1, -10}{2} {3} {4}"
, e.Size, e.CompressedSize,
d.ToString(
"dd-MM-yy"
), d.ToString(
"HH:mm"
),
e.Name);
}
}
}
}
|
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
|
class
ZipAndUnzipFile
{
public
static
void
GetZipAndUnzipFile(){
string
srcFile =
@"..\..\testzip.txt"
;
//准备压缩的文件路径
string
zipFile =
@"..\..\testzip"
;
//压缩后的文件路径
string
unzipFile =
@"..\..\testzip_unzip.txt"
;
//解压后的文件路径
Console.WriteLine(
"使用BZIP开始压缩文件……"
);
if
(BZipFile(srcFile, zipFile +
".bz"
))
//使用BZIP压缩文件
{
Console.WriteLine(
"文件压缩完成"
);
}
else
{
Console.WriteLine(
"文件压缩失败"
);
}
Console.WriteLine(
"使用BZIP开始解压文件……"
);
if
(UnBzipFile(zipFile +
".bz"
, unzipFile))
//使用BZIP解压文件
{
Console.WriteLine(
"文件解压完成"
);
}
else
{
Console.WriteLine(
"文件解压失败"
);
}
Console.WriteLine(
"使用GZIP开始压缩文件……"
);
if
(GZipFile(srcFile, zipFile +
".gz"
))
//使用GZIP压缩文件
{
Console.WriteLine(
"文件压缩完成"
);
}
else
{
Console.WriteLine(
"文件压缩失败"
);
}
Console.WriteLine(
"使用GZIP开始解压文件……"
);
if
(UnGzipFile(zipFile +
".gz"
, unzipFile))
//使用GZIP解压文件
{
Console.WriteLine(
"文件解压完成"
);
}
else
{
Console.WriteLine(
"文件解压失败"
);
}
Console.ReadLine();
}
//使用BZIP压缩文件的方法
static
bool
BZipFile(
string
sourcefilename,
string
zipfilename)
{
bool
blResult;
//表示压缩是否成功的返回结果
//为源文件创建文件流实例,作为压缩方法的输入流参数
FileStream srcFile = File.OpenRead(sourcefilename);
//为压缩文件创建文件流实例,作为压缩方法的输出流参数
FileStream zipFile = File.Open(zipfilename, FileMode.Create);
try
{
//以4096字节作为一个块的方式压缩文件
BZip2.Compress(srcFile, zipFile, 4096);
blResult=
true
;
}
catch
(Exception ee)
{
Console.WriteLine(ee.Message);
blResult=
false
;
}
srcFile.Close();
//关闭源文件流
zipFile.Close();
//关闭压缩文件流
return
blResult;
}
//使用BZIP解压文件的方法
static
bool
UnBzipFile(
string
zipfilename,
string
unzipfilename)
{
bool
blResult;
//表示解压是否成功的返回结果
//为压缩文件创建文件流实例,作为解压方法的输入流参数
FileStream zipFile = File.OpenRead(zipfilename);
//为目标文件创建文件流实例,作为解压方法的输出流参数
FileStream destFile = File.Open(unzipfilename, FileMode.Create);
try
{
BZip2.Decompress(zipFile, destFile);
//解压文件
blResult=
true
;
}
catch
(Exception ee)
{
Console.WriteLine(ee.Message);
blResult=
false
;
}
destFile.Close();
//关闭目标文件流
zipFile.Close();
//关闭压缩文件流
return
blResult;
}
//使用GZIP压缩文件的方法
static
bool
GZipFile(
string
sourcefilename,
string
zipfilename)
{
bool
blResult;
//表示压缩是否成功的返回结果
//为源文件创建读取文件的流实例
FileStream srcFile = File.OpenRead(sourcefilename);
//为压缩文件创建写入文件的流实例,
GZipOutputStream zipFile =
new
GZipOutputStream(File.Open(zipfilename,FileMode.Create));
try
{
byte
[] FileData =
new
byte
[srcFile.Length];
//创建缓冲数据
srcFile.Read(FileData, 0, (
int
)srcFile.Length);
//读取源文件
zipFile.Write(FileData, 0, FileData.Length);
//写入压缩文件
blResult =
true
;
}
catch
(Exception ee)
{
Console.WriteLine(ee.Message);
blResult =
false
;
}
srcFile.Close();
//关闭源文件
zipFile.Close();
//关闭压缩文件
return
blResult;
}
//使用GZIP解压文件的方法
static
bool
UnGzipFile(
string
zipfilename,
string
unzipfilename)
{
bool
blResult;
//表示解压是否成功的返回结果
//创建压缩文件的输入流实例
GZipInputStream zipFile =
new
GZipInputStream(File.OpenRead(zipfilename));
//创建目标文件的流
FileStream destFile = File.Open(unzipfilename, FileMode.Create);
try
{
int
buffersize = 2048;
//缓冲区的尺寸,一般是2048的倍数
byte
[] FileData =
new
byte
[buffersize];
//创建缓冲数据
while
(buffersize>0)
//一直读取到文件末尾
{
buffersize = zipFile.Read(FileData,0,buffersize);
//读取压缩文件数据
destFile.Write(FileData,0,buffersize);
//写入目标文件
}
blResult =
true
;
}
catch
(Exception ee)
{
Console.WriteLine(ee.Message);
blResult =
false
;
}
destFile.Close();
//关闭目标文件
zipFile.Close();
//关闭压缩文件
return
blResult;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
using
System;
using
System.IO;
using
ICSharpCode.SharpZipLib.BZip2;
class
MainClass
{
public
static
void
Main(
string
[] args)
{
if
(args[0] ==
"-d "
) {
// 解压
BZip2.Decompress(File.OpenRead(args[1]), File.Create(Path.GetFileNameWithoutExtension(args[1])),
true
);
}
else
{
//压缩
BZip2.Compress(File.OpenRead(args[0]), File.Create(args[0] +
".bz "
),
true
, 4096);
}
}
}
|
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
|
using
System;
using
System.IO;
using
ICSharpCode.SharpZipLib.GZip;
class
MainClass
{
public
static
void
Main(
string
[] args)
{
if
(args[0] ==
"-d "
) {
// 解压
Stream s =
new
GZipInputStream(File.OpenRead(args[1]));
//生成一个GZipInputStream流,用来打开压缩文件。
//因为GZipInputStream由Stream派生,所以它可以赋给Stream。
//它的构造函数的参数是一个表示要解压的压缩文件所代表的文件流
FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[1]));
//生成一个文件流,它用来生成解压文件
//可以使用System.IO.File的静态函数Create来生成文件流
int
size = 2048;
//指定压缩块的大小,一般为2048的倍数
byte
[] writeData =
new
byte
[size];
//指定缓冲区的大小
while
(
true
) {
size = s.Read(writeData, 0, size);
//读入一个压缩块
if
(size > 0) {
fs.Write(writeData, 0, size);
//写入解压文件代表的文件流
}
else
{
break
;
//若读到压缩文件尾,则结束
}
}
s.Close();
}
else
{
// 压缩
Stream s =
new
GZipOutputStream(File.Create(args[0] +
".gz "
));
//生成一个GZipOutputStream流,用来生成压缩文件。
//因为GZipOutputStream由Stream派生,所以它可以赋给Stream。
FileStream fs = File.OpenRead(args[0]);
/生成一个文件流,它用来打开要压缩的文件
//可以使用System.IO.File的静态函数OpenRead来生成文件流
byte
[] writeData =
new
byte
[fs.Length];
//指定缓冲区的大小
fs.Read(writeData, 0, (
int
)fs.Length);
//读入文件
s.Write(writeData, 0, writeData.Length);
//写入压缩文件
s.Close();
//关闭文件
}
}
|
1
2
|
string
bz2name =
@"C:\t.tar.bz2"
;
BZip2.Decompress(File.OpenRead(bz2name),
new
GZipOutputStream(File.Create(Path.GetFileNameWithoutExtension(bz2name) +
".gz"
)),
true
);
|
1
2
|
string
gzname =
@"C:\test.tar.gz"
;
BZip2.Compress(
new
GZipInputStream(File.OpenRead(gzname)), File.Create(Path.GetFileNameWithoutExtension(gzname) +
".bz2"
),
true
, 5);
|
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
|
using
System;
using
System.IO;
using
ICSharpCode.SharpZipLib.Core;
using
ICSharpCode.SharpZipLib.GZip;
// Extracts the file contained within a GZip to the target dir.
// A GZip can contain only one file, which by default is named the same as the GZip except
// without the extension.
//
public
void
ExtractGZipSample(
string
gzipFileName,
string
targetDir) {
byte
[ ] dataBuffer =
new
byte
[4096];
using
(System.IO.Stream fs =
new
FileStream(gzipFileName, FileMode.Open, FileAccess.Read)) {
using
(GZipInputStream gzipStream =
new
GZipInputStream(fs)) {
// Change this to your needs
string
fnOut = Path.Combine(targetDir, Path.GetFileNameWithoutExtension(gzipFileName));
using
(FileStream fsOut = File.Create(fnOut)) {
StreamUtils.Copy(gzipStream, fsOut, dataBuffer);
}
}
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
using
System;
using
System.IO;
using
ICSharpCode.SharpZipLib.Tar;
public
void
ExtractTar(String tarFileName, String destFolder) {
Stream inStream = File.OpenRead(tarFileName);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(inStream);
tarArchive.ExtractContents(destFolder);
tarArchive.Close();
inStream.Close();
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
using
ICSharpCode.SharpZipLib.GZip;
using
ICSharpCode.SharpZipLib.Tar;
// example: ExtractTGZ(@"c:\temp\test.tar.gz", @"C:\DestinationFolder")
public
void
ExtractTGZ(String gzArchiveName, String destFolder) {
Stream inStream = File.OpenRead(gzArchiveName);
Stream gzipStream =
new
GZipInputStream(inStream);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
tarArchive.ExtractContents(destFolder);
tarArchive.Close();
gzipStream.Close();
inStream.Close();
}
|
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
using
System;
using
System.IO;
using
ICSharpCode.SharpZipLib.Tar;
// Iterates through each file entry within the supplied tar,
// extracting them to the nominated folder.
//
public
void
ExtractTarByEntry(
string
tarFileName,
string
targetDir,
bool
asciiTranslate) {
using
(FileStream fsIn =
new
FileStream(tarFileName, FileMode.Open, FileAccess.Read)) {
TarInputStream tarIn =
new
TarInputStream(fsIn);
TarEntry tarEntry;
while
((tarEntry = tarIn.GetNextEntry()) !=
null
) {
if
(tarEntry.IsDirectory) {
continue
;
}
// Converts the unix forward slashes in the filenames to windows backslashes
//
string
name = tarEntry.Name.Replace(
'/'
, Path.DirectorySeparatorChar);
// Remove any root e.g. '\' because a PathRooted filename defeats Path.Combine
if
(Path.IsPathRooted(name)) {
name = name.Substring(Path.GetPathRoot(name).Length);
}
// Apply further name transformations here as necessary
string
outName = Path.Combine(targetDir, name);
string
directoryName = Path.GetDirectoryName(outName);
Directory.CreateDirectory(directoryName);
// Does nothing if directory exists
FileStream outStr =
new
FileStream(outName, FileMode.Create);
if
(asciiTranslate) {
CopyWithAsciiTranslate(tarIn, outStr);
}
else
{
tarIn.CopyEntryContents(outStr);
}
outStr.Close();
}
tarIn.Close();
}
}
private
void
CopyWithAsciiTranslate(TarInputStream tarIn, Stream outStream) {
byte
[ ] buffer =
new
byte
[4096];
bool
asciiKnown =
false
;
bool
isAscii =
true
;
bool
cr =
false
;
while
(
true
) {
int
numRead = tarIn.Read(buffer, 0, buffer.Length);
if
(numRead <= 0) {
break
;
}
if
(!asciiKnown) {
int
maxCheck = Math.Min(200, numRead);
for
(
int
i = 0; i < maxCheck; i++) {
byte
b = buffer[i];
if
(b < 8 || (b > 13 && b < 32) || b == 255) {
isAscii =
false
;
asciiKnown =
true
;
break
;
}
}
}
if
(isAscii) {
// Convert LF without CR to CRLF. Handle CRLF split over buffers.
for
(
int
i = 0; i < numRead; i++) {
byte
b = buffer[i];
// assuming plain Ascii and not UTF-16
switch
(b) {
case
13:
// CR
cr =
true
;
break
;
case
10:
// LF
if
(!cr)
outStream.WriteByte(13);
else
cr =
false
;
break
;
default
:
cr =
false
;
break
;
}
outStream.WriteByte(b);
}
}
else
{
outStream.Write(buffer, 0, numRead);
}
}
}
|
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
|
using
System;
using
System.IO;
using
ICSharpCode.SharpZipLib.GZip;
using
ICSharpCode.SharpZipLib.Tar;
// Calling example
CreateTarGZ(
@"c:\temp\gzip-test.tar.gz"
,
@"c:\data"
);
private
void
CreateTarGZ(
string
tgzFilename,
string
sourceDirectory) {
Stream outStream = File.Create(tgzFilename);
Stream gzoStream =
new
GZipOutputStream(outStream);
TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzoStream);
// Note that the RootPath is currently case sensitive and must be forward slashes e.g. "c:/temp"
// and must not end with a slash, otherwise cuts off first char of filename
// This is scheduled for fix in next release
tarArchive.RootPath = sourceDirectory.Replace(
'\\'
,
'/'
);
if
(tarArchive.RootPath.EndsWith(
"/"
))
tarArchive.RootPath = tarArchive.RootPath.Remove(tarArchive.RootPath.Length - 1);
AddDirectoryFilesToTar(tarArchive, sourceDirectory,
true
);
tarArchive.Close();
}
private
void
AddDirectoryFilesToTar(TarArchive tarArchive,
string
sourceDirectory,
bool
recurse) {
// Optionally, write an entry for the directory itself.
// Specify false for recursion here if we will add the directory's files individually.
//
TarEntry tarEntry = TarEntry.CreateEntryFromFile(sourceDirectory);
tarArchive.WriteEntry(tarEntry,
false
);
// Write each file to the tar.
//
string
[] filenames = Directory.GetFiles(sourceDirectory);
foreach
(
string
filename
in
filenames) {
tarEntry = TarEntry.CreateEntryFromFile(filename);
tarArchive.WriteEntry(tarEntry,
true
);
}
if
(recurse) {
string
[] directories = Directory.GetDirectories(sourceDirectory);
foreach
(
string
directory
in
directories)
AddDirectoryFilesToTar(tarArchive, directory, recurse);
}
}
|
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
using
System;
using
System.IO;
using
ICSharpCode.SharpZipLib.Tar;
public
void
TarCreateFromStream() {
// Create an output stream. Does not have to be disk, could be MemoryStream etc.
string
tarOutFn =
@"c:\temp\test.tar"
;
Stream outStream = File.Create(tarOutFn);
// If you wish to create a .Tar.GZ (.tgz):
// - set the filename above to a ".tar.gz",
// - create a GZipOutputStream here
// - change "new TarOutputStream(outStream)" to "new TarOutputStream(gzoStream)"
// Stream gzoStream = new GZipOutputStream(outStream);
// gzoStream.SetLevel(3); // 1 - 9, 1 is best speed, 9 is best compression
TarOutputStream tarOutputStream =
new
TarOutputStream(outStream);
CreateTarManually(tarOutputStream,
@"c:\temp\debug"
);
// Closing the archive also closes the underlying stream.
// If you don't want this (e.g. writing to memorystream), set tarOutputStream.IsStreamOwner = false
tarOutputStream.Close();
}
private
void
CreateTarManually(TarOutputStream tarOutputStream,
string
sourceDirectory) {
// Optionally, write an entry for the directory itself.
//
TarEntry tarEntry = TarEntry.CreateEntryFromFile(sourceDirectory);
tarOutputStream.PutNextEntry(tarEntry);
// Write each file to the tar.
//
string
[] filenames = Directory.GetFiles(sourceDirectory);
foreach
(
string
filename
in
filenames) {
// You might replace these 3 lines with your own stream code
using
(Stream inputStream = File.OpenRead(filename)) {
string
tarName = filename.Substring(3);
// strip off "C:\"
long
fileSize = inputStream.Length;
// Create a tar entry named as appropriate. You can set the name to anything,
// but avoid names starting with drive or UNC.
TarEntry entry = TarEntry.CreateTarEntry(tarName);
// Must set size, otherwise TarOutputStream will fail when output exceeds.
entry.Size = fileSize;
// Add the entry to the tar stream, before writing the data.
tarOutputStream.PutNextEntry(entry);
// this is copied from TarArchive.WriteEntryCore
byte
[] localBuffer =
new
byte
[32 * 1024];
while
(
true
) {
int
numRead = inputStream.Read(localBuffer, 0, localBuffer.Length);
if
(numRead <= 0) {
break
;
}
tarOutputStream.Write(localBuffer, 0, numRead);
}
}
tarOutputStream.CloseEntry();
}
// Recurse. Delete this if unwanted.
string
[] directories = Directory.GetDirectories(sourceDirectory);
foreach
(
string
directory
in
directories) {
CreateTarManually(tarOutputStream, directory);
}
}
|
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
|
using
ICSharpCode.SharpZipLib.Zip;
public
void
UpdateExistingZip() {
ZipFile zipFile =
new
ZipFile(
@"c:\temp\existing.zip"
);
// Must call BeginUpdate to start, and CommitUpdate at the end.
zipFile.BeginUpdate();
zipFile.Password =
"whatever"
;
// Only if a password is wanted on the new entry
// The "Add()" method will add or overwrite as necessary.
// When the optional entryName parameter is omitted, the entry will be named
// with the full folder path and without the drive e.g. "temp/folder/test1.txt".
//
zipFile.Add(
@"c:\temp\folder\test1.txt"
);
// Specify the entryName parameter to modify the name as it appears in the zip.
//
zipFile.Add(
@"c:\temp\folder\test2.txt"
,
"test2.txt"
);
// Continue calling .Add until finished.
// Both CommitUpdate and Close must be called.
zipFile.CommitUpdate();
zipFile.Close();
}
|
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
using
System;
using
System.IO;
using
ICSharpCode.SharpZipLib.Zip;
/// <summary>
/// Updates a zip file (in a disk or memorystream) adding the entry contained in the second stream.
/// </summary>
/// <param name="zipStream">Zip file, could be a disk or memory stream. Must be seekable. </param>
/// <param name="entryStream">Stream containing a file to be added. </param>
/// <param name="entryName">Name to appear in the zip entry. </param>
///
public
void
UpdateZipInMemory(Stream zipStream, Stream entryStream, String entryName) {
// The zipStream is expected to contain the complete zipfile to be updated
ZipFile zipFile =
new
ZipFile(zipStream);
zipFile.BeginUpdate();
// To use the entryStream as a file to be added to the zip,
// we need to put it into an implementation of IStaticDataSource.
CustomStaticDataSource sds =
new
CustomStaticDataSource();
sds.SetStream(entryStream);
// If an entry of the same name already exists, it will be overwritten; otherwise added.
zipFile.Add(sds, entryName);
// Both CommitUpdate and Close must be called.
zipFile.CommitUpdate();
// Set this so that Close does not close the memorystream
zipFile.IsStreamOwner =
false
;
zipFile.Close();
// Reposition to the start for the convenience of the caller.
zipStream.Position = 0;
}
public
class
CustomStaticDataSource : IStaticDataSource {
private
Stream _stream;
// Implement method from IStaticDataSource
public
Stream GetSource() {
return
_stream;
}
// Call this to provide the memorystream
public
void
SetStream(Stream inputStream) {
_stream = inputStream;
_stream.Position = 0;
}
}
// This test harness CallingExample method illustrates the use of the UpdateZipInMemory method above.
// In this example, we copy a zip file from disk into a memorystream, update it, and write the memorystream back to
// a (different) disk file. Note that the UpdateZipInMemory method parameters are Stream - any stream will do,
// it does not have to be a memorystream. The zipStream must be seekable, but the entryStream need not.
//
public
void
CallingExample() {
// Read a disk file into memory
MemoryStream msZip =
new
MemoryStream();
FileStream fs = File.OpenRead(
@"c:\temp\existing.zip"
);
// This utility method copies from stream to stream.
// Using StreamUtils.Copy is more efficient than copying whole file into am intermediate byte array.
byte
[] buffer =
new
byte
[4096];
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fs, msZip, buffer);
fs.Close();
// Create an entry to be added.
FileStream fsEntry = File.OpenRead(
@"c:\temp\test1.txt"
);
MemoryStream msEntry =
new
MemoryStream();
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fsEntry, msEntry, buffer);
fsEntry.Close();
// Do the update
UpdateZipInMemory(msZip, msEntry,
"test1updated.txt"
);
// At this point, msZip contains the updated zip. We will write it to a new file.
fs = File.Create(
@"c:\temp\updated.zip"
);
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(msZip, fs,
new
byte
[4096]);
fs.Close();
}
|
1
2
3
4
5
|
FastZip fastZip =
new
FastZip();
bool
recurse =
true
;
// Include all files by recursing through the directory structure
string
filter =
null
;
// Dont filter any files at all
fastZip.CreateZip(
"fileName.zip"
,
@"C:\SourceDirectory"
, recurse, filter);
|
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
|
using
System;
using
System.IO;
using
ICSharpCode.SharpZipLib.Core;
using
ICSharpCode.SharpZipLib.Zip;
private
int
_uptoFileCount;
private
int
_totalFileCount;
public
void
TestFastZipCreate(
string
backupFolderPath) {
_totalFileCount = FolderContentsCount(backupFolderPath);
FastZipEvents events =
new
FastZipEvents();
events.ProcessFile = ProcessFileMethod;
FastZip fastZip =
new
FastZip(events);
fastZip.CreateEmptyDirectories =
true
;
string
zipFileName = Directory.GetParent(backupFolderPath).FullName +
"\\ZipTest.zip"
;
fastZip.CreateZip(zipFileName, backupFolderPath,
true
,
""
);
}
private
void
ProcessFileMethod(
object
sender, ScanEventArgs args) {
_uptoFileCount ++;
int
percentCompleted = _uptoFileCount * 100 / _totalFileCount;
// do something here with a progress bar
// file counts are easier as sizes take more work to calculate, and compression levels vary by file type
string
fileName = args.Name;
// To terminate the process, set args.ContinueRunning = false
if
(fileName ==
"stop on this file"
)
args.ContinueRunning =
false
;
}
// Returns the number of files in this and all subdirectories
private
int
FolderContentsCount(
string
path) {
int
result = Directory.GetFiles(path).Length;
string
[ ] subFolders = Directory.GetDirectories(path);
foreach
(
string
subFolder
in
subFolders) {
result += FolderContentsCount(subFolder);
}
return
result;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
C#
using
System;
using
ICSharpCode.SharpZipLib.Zip;
public
void
TestFastZipUnpack(
string
zipFileName,
string
targetDir) {
FastZip fastZip =
new
FastZip();
string
fileFilter =
null
;
// Will always overwrite if target filenames already exist
fastZip.ExtractZip(zipFileName, targetDir, fileFilter);
}
|
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
|
using
System;
using
System.Windows.Forms;
using
ICSharpCode.SharpZipLib.Core;
using
ICSharpCode.SharpZipLib.Zip;
private
bool
_stop;
public
void
TestFastZipUnpack(
string
zipFileName,
string
targetDir) {
// Set the method that will be called on each file before extraction but after the OverwritePrompt (if applicable)
FastZipEvents events =
new
FastZipEvents();
events.ProcessFile = ProcessFileMethod;
FastZip fastZip =
new
FastZip(events);
// To conditionally extract files in FastZip, use the fileFilter and directoryFilter arguments.
// The filter is a list of regex values separated with semi-colon. An entry starting with - is an exclusion.
// See the NameFilter class for more details.
// The following expression includes all name ending in '.dat' with the exception of 'dummy.dat'
string
fileFilter =
@"+\.dat$;-^dummy\.dat$"
;
string
directoryFilter =
null
;
bool
restoreDateTime =
true
;
// Will prompt to overwrite if target filenames already exist
fastZip.ExtractZip(zipFileName, targetDir, FastZip.Overwrite.Prompt, OverwritePrompt,
fileFilter, directoryFilter, restoreDateTime);
}
private
bool
OverwritePrompt(
string
fileName) {
// In this method you can choose whether to overwrite a file.
DialogResult dr = MessageBox.Show(
"Overwrite "
+ fileName,
"Overwrite?"
, MessageBoxButtons.YesNoCancel);
if
(dr == DialogResult.Cancel) {
_stop =
true
;
// Must return true if we want to abort processing, so that the ProcessFileMethod will be called.
// When the ProcessFileMethod sets ContinueRunning false, processing will immediately stop.
return
true
;
}
return
dr == DialogResult.Yes;
}
private
void
ProcessFileMethod(
object
sender, ScanEventArgs args) {
string
fileName = args.Name;
// To stop all further processing, set args.ContinueRunning = false
if
(_stop) {
args.ContinueRunning =
false
;
}
}
|
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
|
/// <summary>
/// Zip压缩与解压缩
/// </summary>
public
class
ZipHelper
{
/// <summary>
/// 压缩单个文件
/// </summary>
/// <param name="fileToZip">要压缩的文件</param>
/// <param name="zipedFile">压缩后的文件</param>
/// <param name="compressionLevel">压缩等级</param>
/// <param name="blockSize">每次写入大小</param>
public
static
void
ZipFile(
string
fileToZip,
string
zipedFile,
int
compressionLevel,
int
blockSize)
{
//如果文件没有找到,则报错
if
(!System.IO.File.Exists(fileToZip))
{
throw
new
System.IO.FileNotFoundException(
"指定要压缩的文件: "
+ fileToZip +
" 不存在!"
);
}
using
(System.IO.FileStream ZipFile = System.IO.File.Create(zipedFile))
{
using
(ZipOutputStream ZipStream =
new
ZipOutputStream(ZipFile))
{
using
(System.IO.FileStream StreamToZip =
new
System.IO.FileStream(fileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
string
fileName = fileToZip.Substring(fileToZip.LastIndexOf(
"\\"
) + 1);
ZipEntry ZipEntry =
new
ZipEntry(fileName);
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(compressionLevel);
byte
[] buffer =
new
byte
[blockSize];
int
sizeRead = 0;
try
{
do
{
sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
ZipStream.Write(buffer, 0, sizeRead);
}
while
(sizeRead > 0);
}
catch
(System.Exception ex)
{
throw
ex;
}
StreamToZip.Close();
}
ZipStream.Finish();
ZipStream.Close();
}
ZipFile.Close();
}
}
/// <summary>
/// 压缩单个文件
/// </summary>
/// <param name="fileToZip">要进行压缩的文件名</param>
/// <param name="zipedFile">压缩后生成的压缩文件名</param>
public
static
void
ZipFile(
string
fileToZip,
string
zipedFile)
{
//如果文件没有找到,则报错
if
(!File.Exists(fileToZip))
{
throw
new
System.IO.FileNotFoundException(
"指定要压缩的文件: "
+ fileToZip +
" 不存在!"
);
}
using
(FileStream fs = File.OpenRead(fileToZip))
{
byte
[] buffer =
new
byte
[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
using
(FileStream ZipFile = File.Create(zipedFile))
{
using
(ZipOutputStream ZipStream =
new
ZipOutputStream(ZipFile))
{
string
fileName = fileToZip.Substring(fileToZip.LastIndexOf(
"\\"
) + 1);
ZipEntry ZipEntry =
new
ZipEntry(fileName);
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(5);
ZipStream.Write(buffer, 0, buffer.Length);
ZipStream.Finish();
ZipStream.Close();
}
}
}
}
/// <summary>
/// 压缩多层目录
/// </summary>
/// <param name="strDirectory">The directory.</param>
/// <param name="zipedFile">The ziped file.</param>
public
static
void
ZipFileDirectory(
string
strDirectory,
string
zipedFile)
{
using
(System.IO.FileStream ZipFile = System.IO.File.Create(zipedFile))
{
using
(ZipOutputStream s =
new
ZipOutputStream(ZipFile))
{
ZipSetp(strDirectory, s,
""
);
}
}
}
/// <summary>
/// 递归遍历目录
/// </summary>
/// <param name="strDirectory">The directory.</param>
/// <param name="s">The ZipOutputStream Object.</param>
/// <param name="parentPath">The parent path.</param>
private
static
void
ZipSetp(
string
strDirectory, ZipOutputStream s,
string
parentPath)
{
if
(strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)
{
strDirectory += Path.DirectorySeparatorChar;
}
Crc32 crc =
new
Crc32();
string
[] filenames = Directory.GetFileSystemEntries(strDirectory);
foreach
(
string
file
in
filenames)
// 遍历所有的文件和目录
{
if
(Directory.Exists(file))
// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
{
string
pPath = parentPath;
pPath += file.Substring(file.LastIndexOf(
"\\"
) + 1);
pPath +=
"\\"
;
ZipSetp(file, s, pPath);
}
else
// 否则直接压缩文件
{
//打开压缩文件
using
(FileStream fs = File.OpenRead(file))
{
byte
[] buffer =
new
byte
[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string
fileName = parentPath + file.Substring(file.LastIndexOf(
"\\"
) + 1);
ZipEntry entry =
new
ZipEntry(fileName);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
}
}
}
/// <summary>
/// 解压缩一个 zip 文件。
/// </summary>
/// <param name="zipedFile">The ziped file.</param>
/// <param name="strDirectory">The STR directory.</param>
/// <param name="password">zip 文件的密码。</param>
/// <param name="overWrite">是否覆盖已存在的文件。</param>
public
void
UnZip(
string
zipedFile,
string
strDirectory,
string
password,
bool
overWrite)
{
if
(strDirectory ==
""
)
strDirectory = Directory.GetCurrentDirectory();
if
(!strDirectory.EndsWith(
"\\"
))
strDirectory = strDirectory +
"\\"
;
using
(ZipInputStream s =
new
ZipInputStream(File.OpenRead(zipedFile)))
{
s.Password = password;
ZipEntry theEntry;
while
((theEntry = s.GetNextEntry()) !=
null
)
{
string
directoryName =
""
;
string
pathToZip =
""
;
pathToZip = theEntry.Name;
if
(pathToZip !=
""
)
directoryName = Path.GetDirectoryName(pathToZip) +
"\\"
;
string
fileName = Path.GetFileName(pathToZip);
Directory.CreateDirectory(strDirectory + directoryName);
if
(fileName !=
""
)
{
if
((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName)))
{
using
(FileStream streamWriter = File.Create(strDirectory + directoryName + fileName))
{
int
size = 2048;
byte
[] data =
new
byte
[2048];
while
(
true
)
{
size = s.Read(data, 0, data.Length);
if
(size > 0)
streamWriter.Write(data, 0, size);
else
break
;
}
streamWriter.Close();
}
}
}
}
s.Close();
}
}
}
|
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
|
public
static
MemoryStream CreateGzipStream(Dictionary<
string
, MemoryStream> DicEntryName_Stream)
{
int
count = 0;
//Uncomment following line if you want to save to a file
//Stream outputFileStream = File.Create("TGZ_Output.tgz");
MemoryStream outputMemStream =
new
MemoryStream();
GZipOutputStream gzoStream =
new
GZipOutputStream(outputMemStream);
ICSharpCode.SharpZipLib.Tar.TarOutputStream TarStream =
new
TarOutputStream(gzoStream);
foreach
(KeyValuePair<
string
, MemoryStream> custKeyVal
in
DicEntryName_Stream)
{
TarEntry newEntry = TarEntry.CreateTarEntry(custKeyVal.Key);
newEntry.Size = custKeyVal.Value.Length;
TarStream.PutNextEntry(newEntry);
StreamUtils.Copy(custKeyVal.Value, TarStream,
new
byte
[4096]);
TarStream.CloseEntry();
count++;
}
TarStream.IsStreamOwner =
false
;
// False stops the Close also Closing the underlying stream.
TarStream.Close();
// Must finish the ZipOutputStream before using outputMemStream.
gzoStream.Close();
return
outputMemStream;
}
|
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
|
public
void
ProcessRequest(HttpContext context)
{
List<
string
> fileNames = GetFileNames();
context.Response.ContentType =
"application/x-zip-compressed"
;
context.Response.AppendHeader(
"content-disposition"
,
"attachment; filename=files.zip"
);
context.Response.ContentEncoding = Encoding.Default;
context.Response.Charset =
""
;
byte
[] buffer =
new
byte
[1024 * 8];
using
(ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutput =
new
ICSharpCode.SharpZipLib.Zip.ZipOutputStream(context.Response.OutputStream))
{
foreach
(
string
fileName
in
fileNames)
{
ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry =
new
ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
zipOutput.PutNextEntry(zipEntry);
using
(
var
fread = System.IO.File.OpenRead(fileName))
{
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fread, zipOutput, buffer);
}
}
zipOutput.Finish();
}
context.Response.Flush();
context.Response.End();
}
|
1
2
3
4
|
MemoryStream outputMemStream =
new
MemoryStream();
using
(ZipOutputStream zipOutput =
new
ZipOutputStream(outputMemStream)) {
// Use zipOutput stream as normal
...
|
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
|
public
IEnumerable<
string
> ExtractTar(Stream archiveStream)
{
var
archive = TarArchive.CreateInputTarArchive(archiveStream);
var
tarStream =
new
TarInputStream(archiveStream);
var
tarEntry = tarStream.GetNextEntry();
while
(tarEntry !=
null
)
{
yield
return
tarEntry.Name;
}
}
Stream Extract(Stream archiveStream,
string
type)
{
Stream sharpZipStream;
switch
(type)
{
case
"z"
: sharpZipStream =
new
InflaterInputStream(archiveStream);
break
;
case
"gzip"
: sharpZipStream =
new
GZipInputStream(archiveStream);
break
;
case
"bzip2"
: sharpZipStream =
new
BZip2InputStream(archiveStream);
break
;
case
"tar"
: sharpZipStream =
new
TarInputStream(archiveStream);
break
;
default
: sharpZipStream =
null
;
break
;
}
var
streamPipe =
new
SimpleStreamPipe();
var
dataBuffer =
new
byte
[BufferSize];
using
(archiveStream)
using
(sharpZipStream)
using
(
var
outStream = streamPipe.GetInput())
{
StreamUtils.Copy(sharpZipStream, outStream, dataBuffer);
}
return
streamPipe.GetOutput();
}
|