您的位置:首页 > 编程语言 > C#

c#递归压缩文件夹方法

2016-07-01 14:22 555 查看
#region 私有方法
/// <summary>
/// 递归压缩文件夹方法 //转载请注明来自 http://www.shang11.com /// </summary>
private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName)
{
bool res = true;
string[] folders, filenames;
ZipEntry entry = null;
FileStream fs = null;
Crc32 crc = new Crc32();
try
{
entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/"));
s.PutNextEntry(entry);
s.Flush();
filenames = Directory.GetFiles(FolderToZip);
foreach (string file in filenames)
{
fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file)));
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);
}
}
catch
{
res = false;
}
finally
{
if (fs != null)
{
fs.Close();
fs = null;
}
if (entry != null)
{
entry = null;
}
GC.Collect();
GC.Collect(1);
}
folders = Directory.GetDirectories(FolderToZip);
foreach (string folder in folders)
{
if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
{
return false;
}
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息