這邊簡單示範如何 unzip a zipped directory.
using System;以上程式碼未做 exception handling,請小心服用。如果給的檔案不能 unzip,我們可能會吃到 ICSharpCode.SharpZipLib.SharpZipBaseException 例外;如果 dest 給錯,也可能會吃到 DirectoryNotFoundException 例外。
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
static void Unzip(string src, string dest) {
if (!File.Exists(src)) {
throw new FileNotFoundException();
}
using (ZipInputStream reader
= new ZipInputStream(File.OpenRead(src))) {
ZipEntry entry;
while ((entry = reader.GetNextEntry()) != null) {
string dir_name = Path.GetDirectoryName(entry.Name);
string dest_dir = Path.Combine(dest, dir_name);
Directory.CreateDirectory(dest_dir);
string file_name = Path.GetFileName(entry.Name);
if (String.IsNullOrEmpty(file_name)) {
continue;
}
using (FileStream writer
= File.Create(Path.Combine(dest_dir, file_name)))
{
byte[] data = new byte[2048];
while (true) {
int size = reader.Read(data, 0, data.Length);
if (size > 0) {
writer.Write(data, 0, size);
} else {
break;
}
}
}
}
}
}
沒有留言:
張貼留言