2013-03-17 654 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