2012-08-24 119 views
1

隨着SharpZip LIB我可以很容易地提取從ZIP檔案文件:C#:只提取一個壓縮文件(沒有文件夾)

FastZip fz = new FastZip(); 
string path = "C:/bla.zip"; 
fz.ExtractZip(bla,"C:/Unzips/",".*"); 

然而,這把未壓縮的文件夾中的輸出目錄。 假設我想要的bla.zip中有一個foo.txt文件。有沒有簡單的方法來提取它並將其放置在輸出目錄中(不包​​含文件夾)?

回答

2

FastZip似乎沒有提供更改文件夾的方法,但是the "manual" way of doing supports this

如果你看看他們的榜樣:

public void ExtractZipFile(string archiveFilenameIn, string outFolder) { 
    ZipFile zf = null; 
    try { 
     FileStream fs = File.OpenRead(archiveFilenameIn); 
     zf = new ZipFile(fs); 

     foreach (ZipEntry zipEntry in zf) { 
      if (!zipEntry.IsFile) continue; // Ignore directories 

      String entryFileName = zipEntry.Name; 
      // to remove the folder from the entry: 
      // entryFileName = Path.GetFileName(entryFileName); 

      byte[] buffer = new byte[4096];  // 4K is optimum 
      Stream zipStream = zf.GetInputStream(zipEntry); 

      // Manipulate the output filename here as desired. 
      String fullZipToPath = Path.Combine(outFolder, entryFileName); 
      string directoryName = Path.GetDirectoryName(fullZipToPath); 
      if (directoryName.Length > 0) 
       Directory.CreateDirectory(directoryName); 

      using (FileStream streamWriter = File.Create(fullZipToPath)) { 
       StreamUtils.Copy(zipStream, streamWriter, buffer); 
      } 
     } 
    } finally { 
     if (zf != null) { 
      zf.IsStreamOwner = true;stream 
      zf.Close(); 
     } 
    } 
} 

當他們注意,而不是寫:

String entryFileName = zipEntry.Name; 

你可以寫:

String entryFileName = Path.GetFileName(entryFileName) 

刪除的文件夾。

1

假設你知道這是在zip唯一的文件(不文件夾):

using(ZipFile zip = new ZipFile(zipStm)) 
{ 
    foreach(ZipEntry ze in zip) 
    if(ze.IsFile)//must be our foo.txt 
    { 
     using(var fs = new FileStream(@"C:/Unzips/foo.txt", FileMode.OpenOrCreate, FileAccess.Write)) 
     zip.GetInputStream(ze).CopyTo(fs); 
     break; 
    } 
} 

如果您需要處理其他的可能性,或如獲取壓縮條目的名稱,複雜性相應地增加。