C#实现文件压缩与解压功能的示例代码
c#实现文件压缩与解压功能的示例代码
压缩
private void skinbutton1_click(object sender, eventargs e) { filesuploadfor.zipdirectory(foldertozip.text,zipedfilename.text); filesuploadfor.displaylistboxmsg("压缩完成"); }
zipdirectory
压缩用的是库函数
/// /// 压缩文件夹 /// /// 需要压缩的文件夹 /// 压缩后的zip完整文件名 public static void zipdirectory(string foldertozip, string zipedfilename) { zipdirectory(foldertozip, zipedfilename, string.empty, true, string.empty, string.empty, true); } /// /// 压缩文件夹 /// /// 需要压缩的文件夹 /// 压缩后的zip完整文件名(如d:\test.zip) /// 如果文件夹下有子文件夹,是否递归压缩 /// 解压时需要提供的密码 /// 文件过滤正则表达式 /// 文件夹过滤正则表达式 /// 是否压缩文件中的空文件夹 public static void zipdirectory(string foldertozip, string zipedfilename, string password, bool isrecurse, string fileregexfilter, string directoryregexfilter, bool iscreateemptydirectories) { fastzip fastzip = new fastzip(); fastzip.createemptydirectories = iscreateemptydirectories; fastzip.password = password; fastzip.createzip(zipedfilename, foldertozip, isrecurse, fileregexfilter, directoryregexfilter); }
解压缩
private void skinbutton2_click(object sender, eventargs e) { filesuploadfor.unzip(zipedfilename.text,""); filesuploadfor.displaylistboxmsg("解压缩完成"); }
unzip
解压用的是库函数
/// /// 功能:解压zip格式的文件。 /// /// 压缩文件路径 /// 解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 /// 解压是否成功 public void unzip(string zipfilepath, string unzipdir) { if (zipfilepath == string.empty) { throw new exception("压缩文件不能为空!"); } if (!file.exists(zipfilepath)) { throw new filenotfoundexception("压缩文件不存在!"); } //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 if (unzipdir == string.empty) unzipdir = zipfilepath.replace(path.getfilename(zipfilepath), path.getfilenamewithoutextension(zipfilepath)); if (!unzipdir.endswith("/")) unzipdir += "/"; if (!directory.exists(unzipdir)) directory.createdirectory(unzipdir); using (var s = new zipinputstream(file.openread(zipfilepath))) { zipentry theentry; while ((theentry = s.getnextentry()) != null) { string directoryname = path.getdirectoryname(theentry.name); string filename = path.getfilename(theentry.name); if (!string.isnullorempty(directoryname)) { directory.createdirectory(unzipdir + directoryname); } if (directoryname != null && !directoryname.endswith("/")) { } if (filename != string.empty) { using (filestream streamwriter = file.create(unzipdir + theentry.name)) { int size; byte[] data = new byte[2048]; while (true) { size = s.read(data, 0, data.length); if (size > 0) { streamwriter.write(data, 0, size); } else { break; } } } } } } }