最近,一些需求,會讓客戶打包自己的 ZIP 傳上來,我要解壓縮,但是我不希望她有一些我指定的檔案跟檔名,稍微研究一下,就把程式碼在部落格紀錄一下,讓自己之後會比較快複習..

看上列圖示,這裡面有檔案夾 TESTA,TESTB,TESTX 檔案是 a.txt , b.txt , x.txt ,然後我是要排除 x.txt 還有 TESTX 的檔案和檔案夾
C# Code :
//解壓目的地目錄
var outputTargetDirectory = AppDomain.CurrentDomain.BaseDirectory + "lab" + Path.DirectorySeparatorChar + "result" + Path.DirectorySeparatorChar;
//ZIP 檔案來源
var zipFileLocation = AppDomain.CurrentDomain.BaseDirectory + "lab" + Path.DirectorySeparatorChar + "sample.zip";
//不允許的檔案夾 後面記得加上 /
string[] notAllowDirs = { "TESTX/" };
//不允許的檔名
string[] notAllowFiles = { "x.txt" };
ZipInputStream s = new ZipInputStream(File.OpenRead(zipFileLocation));
ZipEntry zipEntry;
while ((zipEntry = s.GetNextEntry()) != null)
{
//排除黑名單的檔案夾
if (zipEntry.IsDirectory && notAllowDirs.Any(x => x.ToLower() == zipEntry.Name.ToLower()))
{
continue;
}
//排除黑名單的檔案
if (zipEntry.IsFile && notAllowFiles.Any(x => x.ToLower() == zipEntry.Name.ToLower()))
{
continue;
}
//建立目錄
if (zipEntry.IsDirectory)
{
Directory.CreateDirectory(outputTargetDirectory + zipEntry.Name);
}
string fileName = Path.GetFileName(zipEntry.Name);
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(outputTargetDirectory + zipEntry.Name);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
之後,解壓縮出來就不會有 TESTX 還有 x.txt
如果你是要找全部的解壓縮網路上很多範例,這邊就不贅述了
參考文章:
https://stackoverflow.com/questions/8313791/sharpziplib-examine-and-select-contents-of-a-zip-filehttps://dotblogs.com.tw/yc421206/2013/09/05/116442