2013-03-17 659 views
9

我使用標準的VB.NET庫來提取和壓縮文件。它也可以工作,但是當我必須提取並且文件已經存在時,問題就來了。System.IO.Compression和ZipFile - 提取並覆蓋

代碼我用

進口:

Imports System.IO.Compression 

方法我打電話的時候,它崩潰

ZipFile.ExtractToDirectory(archivedir, BaseDir) 

archivedir和的BaseDir設置爲好,其實,如果沒有文件工作覆蓋。這個問題恰恰出現在那裏。

如何在不使用第三方庫的情況下覆蓋提取文件?

(注意:我使用的是作爲參考System.IO.Compression和System.IO.Compression.Filesystem)

由於文件走在多個文件夾在已經存在的文件我會避免手動

IO.File.Delete(..) 

回答

11

使用ExtractToFile以覆蓋爲真,以覆蓋現有文件具有相同的名稱作爲目標文件

Dim zipPath As String = "c:\example\start.zip" 
    Dim extractPath As String = "c:\example\extract" 

    Using archive As ZipArchive = ZipFile.OpenRead(zipPath) 
     For Each entry As ZipArchiveEntry In archive.Entries 
      entry.ExtractToFile(Path.Combine(extractPath, entry.FullName), True) 
     Next 
    End Using 
+0

似乎工作更多,但它現在不適用於愚蠢的系統文件,如「Thumbs.db」,使執行和覆蓋失敗。有任何想法嗎? – user1714647 2013-03-18 18:24:45

+1

另一個問題:它似乎不復制文件,如果必須包含它們的文件夾不存在。 – user1714647 2013-03-18 19:17:53

+0

我會建議使用自定義壓縮邏輯並去除所有不需要的文件,如「Thumbs.db」;對於第二個使用下一個代碼如果IO.Directory.Exists(路徑)= False然後IO.Directory.CreateDirectory(路徑) – volody 2013-03-18 19:26:19

6

我發現下面的imple通過努力解決上述問題,無誤地運行併成功覆蓋現有文件並根據需要創建目錄。

 ' Extract the files - v2 
     Using archive As ZipArchive = ZipFile.OpenRead(fullPath) 
      For Each entry As ZipArchiveEntry In archive.Entries 
       Dim entryFullname = Path.Combine(ExtractToPath, entry.FullName) 
       Dim entryPath = Path.GetDirectoryName(entryFullName) 
       If (Not (Directory.Exists(entryPath))) Then 
        Directory.CreateDirectory(entryPath) 
       End If 

       Dim entryFn = Path.GetFileName(entryFullname) 
       If (Not String.IsNullOrEmpty(entryFn)) Then 
        entry.ExtractToFile(entryFullname, True) 
       End If 
      Next 
     End Using