public
static
bool
ZipFileDictory
(
string
filePath,
string
saveZipPath
)
bool
flag =
true
;
if
(!Directory.Exists(filePath))
return
false
;
if
(
string
.IsNullOrEmpty(saveZipPath))
saveZipPath +=
".zip"
;
ZipOutputStream zipOutputStream =
new
ZipOutputStream(File.Create(saveZipPath));
zipOutputStream.SetLevel(
6
);
flag = ZipFileDictory(filePath,zipOutputStream,
""
);
zipOutputStream.Finish();
zipOutputStream.Close();
return
flag;
3.递归进行文件压缩
/// <summary>
/// 递归压缩文件夹方法
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="s">zip文件流</param>
/// <param name="ParentFolderName">父类文件名称</param>
/// <returns></returns>
private static bool ZipFileDictory(string filePath, ZipOutputStream s, string ParentFolderName)
bool flag = true
string[] folders, filenames
ZipEntry entry = null
FileStream fs = null
//Crc32 crc = new Crc32()
//创建当前文件夹
entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(filePath) + "/"))
s.PutNextEntry(entry)
s.Flush()
//先压缩文件,再递归压缩文件夹
filenames = Directory.GetFiles(filePath)
foreach (string file in filenames)
itemCount++
ItemCompressed?.Invoke(itemCount)
//打开压缩文件
fs = File.OpenRead(file)
byte[] buffer = new byte[avg]
entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(filePath) + "/" + Path.GetFileName(file)))
DateTime = DateTime.Now,
Size = fs.Length
s.PutNextEntry(entry)
for (int i = 0
if (i + avg > fs.Length)
//不足100MB的部分写剩余部分
buffer = new byte[fs.Length - i]
fs.Read(buffer, 0, buffer.Length)
s.Write(buffer, 0, buffer.Length)
catch
flag = false
finally
if (fs != null)
fs.Close()
GC.Collect()
GC.Collect(1)
folders = Directory.GetDirectories(filePath)
foreach (string folder in folders)
if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(filePath))))
return false
return flag
二、在接口中调用压缩方法即可
1.如下图所示,这是我压缩之前的文件
2.如下图所示,这是我的压缩方法调用
3.如下图所示,我的文件已经被压缩成功了
以上就是我自己整理的一个简单压缩文件的方法,大家有更加好用的方法,欢迎来评论区一起探讨!!!