C# 处理 ZIP 压缩档

C# 本身並無提供ZIP相關的類別,我們可使用 SharpZipLib 這個類別庫來處理壓縮檔,有需要可到 SharpZipLib 官方網站下載:
http://www.icsharpcode.net/OpenSource/SharpZipLib/

=======================================================

如下的 Method,可以將一個資料夾內所有的檔案壓縮成一 .ZIP 檔:

// 傳入參數: 來源路徑, 目的壓縮檔名(.zip), 壓縮比( 0=僅儲存, 9=最高壓縮比 )
public static void Compress(string dir, string zipFileName, int level)
{
string[] filenames = Directory.GetFiles(dir);
byte[] buffer = new byte[4096];

using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFileName)))
{
// 設定壓縮比
s.SetLevel(level);

// 逐一將資料夾內的檔案抓出來壓縮,並寫入至目的檔(.ZIP)
foreach (string filename in filenames)
{
ZipEntry entry = new ZipEntry(filename);
s.PutNextEntry(entry);

using (FileStream fs = File.OpenRead(filename))
StreamUtils.Copy(fs, s, buffer);
}
}
}

呼叫 Compress ,將 C:\851_ICSharpCode.SharpZipLib_20 資料夾下所有的檔案壓縮成 test.zip,壓縮比 5

Compress("C:\\0851_ICSharpCode.SharpZipLib_20", "C:\\Downloads\\test.zip", 5);

=======================================================

然後使用如下的方法,可以列舉壓縮檔內所有的檔案:

// 傳入參數: 來源壓縮檔檔名
public static void List(string zipFile)
{
if (File.Exists(zipFile))
{
ZipFile zip = new ZipFile(zipFile);

foreach (ZipEntry entry in zip)
{
if (entry.IsFile)
Console.WriteLine(entry.Name);
}
}
else
Console.WriteLine(zipFile + " 不存在");
}

呼叫 List ,將 test.zip 這壓縮檔所包含的檔案印出:

List("C:\\Downloads\\test.zip");


=======================================================

解壓縮:

// 解壓縮檔案,傳入參數: 來源壓縮檔, 解壓縮後的目的路徑
public static void Uncompress(string zipFileName, string targetPath)
{
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFileName)))
{
// 若目的路徑不存在,則先建立路徑
DirectoryInfo di = new DirectoryInfo(targetPath);

if
(!di.Exists)
di.Create();

ZipEntry theEntry;

// 逐一取出壓縮檔內的檔案(解壓縮)
while ((theEntry = s.GetNextEntry()) != null)
{
int size = 2048;
byte[] data = new byte[2048];

Console.WriteLine("正在解壓縮: " + GetBasename(theEntry.Name));

// 寫入檔案
using (FileStream fs = new FileStream(di.FullName + "
\\" + GetBasename(theEntry.Name), FileMode.Create))
{
while (true)
{
size = s.Read(data, 0, data.Length);

if
(size > 0)
fs.Write(data, 0, size);
else
break;
}

}
}
}
}

// 取得檔名(去除路徑)
public static string GetBasename(string fullName)
{
string result;
int lastBackSlash = fullName.LastIndexOf("
\\");
result = fullName.Substring(lastBackSlash + 1);
"

return result;
}

呼叫 Upcompress ,將 test.zip 這壓縮檔解壓縮至 C:\Downloads\test 目錄下:

Uncompress("C:\\Downloads\\test.zip", "C:\\Downloads\\test");

文章出自:http://blog.xuite.net/cppbuilder/blog/9576384

Tag标签: C#ZIP
posted on 2010-05-08 10:31 发布:慧晓 阅读(274) 评论(0) 收藏 所属分类: ASP.NET(C#)
  • 评论
  • 点击刷新
  • [使用Ctrl+Enter键可以直接提交]

表情图标

[smile][confused][cool][cry][eek][angry][wink][sweat][lol][stun][razz][redface][rolleyes][sad][yes][no][heart][star][music][idea]
Advertise
Category
Time Counter

离十一还有

Recent Article
Statistics
Recent Comments
Archive
Links
Support
《良机》 鲜果阅读器订阅图标
 
TOP