/// <summary>
/// 文件夹下的文件以及子目录的文件进行压缩(多层递归)
/// </summary>
/// <param name="dirPath">需要压缩的文件夹路径("C:\\data")</param>
/// <param name="GzipFileName">压缩后保存的路径("C:\\data\\test.zip")</param>
public static void CompressDirectory(string dirPath, string GzipFileName)
{
//创建压缩文件
FileStream pCompressFile = new FileStream(GzipFileName, FileMode.Create);
using (ZipOutputStream zipoutputstream = new ZipOutputStream(pCompressFile))
{
Crc32 crc = new Crc32();
Dictionary<string, DateTime> fileList = GetAllFies(dirPath);
foreach (KeyValuePair<string, DateTime> item in fileList)
{
FileStream fs = new FileStream(item.Key.ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
// FileStream fs = File.OpenRead(item.Key.ToString());
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(item.Key.Substring(dirPath.Length));
entry.DateTime = item.Value;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipoutputstream.PutNextEntry(entry);
zipoutputstream.Write(buffer, 0, buffer.Length);
}
}
}
/// <summary>
/// 获取所有文件
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
private static Dictionary<string, DateTime> GetAllFies(string dir)
{
Dictionary<string, DateTime> FilesList = new Dictionary<string, DateTime>();
if (!Directory.Exists(dir))
{
throw new System.IO.FileNotFoundException("目录:” +fileDire.FullName + “没有找到!");
}
var dirs = new DirectoryInfo[] {
new DirectoryInfo(dir)
};
GetAllDirsFiles(dirs, FilesList);
return FilesList;
}
/// <summary>
/// 获取一个文件夹下的所有文件夹里的文件
/// </summary>
/// <param name="dirs"></param>
/// <param name="filesList"></param>
private static void GetAllDirsFiles(DirectoryInfo[] dirs, Dictionary<string, DateTime> filesList)
{
foreach (DirectoryInfo dir in dirs)
{
foreach (FileInfo file in dir.GetFiles("."))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
GetAllDirsFiles(dir.GetDirectories(), filesList);
}
}
直接调用CompressDirectory方法即可