序言:
在我接触Git和SVN之前,我最常用的保存数据的办法就是把文件夹压缩成一个zip文件,添加上时间戳。下面是我在学习C#的文件操作之后做的一个练习,使用开源的ICSharpZipLib来压缩文件夹并保存到指定的目录,还附带简单的日志文件。
简介:
ICSharpZipLib是一个开源的应用于.NET平台的开源类库。运用C#语言和这个类库,我们可以很轻松地创建和操作压缩文件,例如:Zip,GZip, Tar and BZip2。
源代码:
废话不多说,咱直接上源代码。说实话,使用ICSharpZipLib的博客应该也有很多,但是试了一下好多不能用。下面的这个类是我根据一个印度程序员(英文网站上的,不知道到底是啥名字,但是长得很三哥!)的博客改写的。测试过的哦,亲!
1: class CompressFolderIntoZip
2: {
3: /// <summary>
4: /// 用来进行文件夹的压缩,输入参数源文件夹路径和目标文件夹路径即可。
5: /// </summary>
6: /// <param name="sourceFolderPath"></param>
7: /// <param name="destFolderPath"></param>
8: /// <returns></returns>
9: public static bool CompressFolder(string sourceFolderPath, string destFolderPath)
10: {
11: try
12: {
13: //文件名=文件夹名+时间戳+.zip;
14: string zipFileName = destFolderPath + "\\" +
15: sourceFolderPath.Substring(sourceFolderPath.LastIndexOf('\\') + 1)
16: + "(" + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + ").zip";
17: ZipFile zipFile = ZipFile.Create(zipFileName);
18: zipFile.BeginUpdate();
19: //压缩文件夹时默认采用源文件夹的上一级作为根目录;
20: AddFolderToZip(zipFile,
21: sourceFolderPath.Substring(0, sourceFolderPath.LastIndexOf('\\')),
22: sourceFolderPath);
23: zipFile.CommitUpdate();
24: zipFile.Close();
25: }
26: catch (Exception exception)
27: {
28: Console.WriteLine(exception.ToString());
29: return false;
30: }
31: return true;
32: }
33:
34: /// <summary>
35: /// 该方法用来实现文件夹及其中文件和子文件夹的递归压缩
36: /// ZipFile zipFile=ZipFile.Create(string <zipfilename>)
37: /// folderPath是需要压缩的文件夹
38: /// root是压缩文件中的根目录,如果folderPath=@"C:\Test"而root=@"C:\"那么打开压缩文件会先显示一个名为Test的文件夹。如果folderPath=@"C:\Test"而root=@"C:\Test"那么压缩文件打开会直接显示Test文件夹下所有文件盒子文件夹。
39: /// </summary>
40: /// <param name="zipFile"></param>
41: /// <param name="root"></param>
42: /// <param name="folderPath"></param>
43: private static void AddFolderToZip(ZipFile zipFile, string root, string folderPath)
44: {
45: string relativePath = folderPath.Substring(root.Length);
46: if (relativePath.Length > 0)
47: {
48: zipFile.AddDirectory(relativePath);
49: }
50:
51: foreach (string file in Directory.GetFiles(folderPath))
52: {
53: relativePath = file.Substring(root.Length);
54: zipFile.Add(file, relativePath);
55: }
56:
57: foreach (string subFolder in Directory.GetDirectories(folderPath))
58: {
59: AddFolderToZip(zipFile, root, subFolder);
60: }
61: }
62: }