文件名 'filename' 已经存在 VB .NET

The filename 'filename' already exists VB .NET

我想提取存档。 但问题是,当代码运行时,它会抛出以下异常:

System.IO.IOException: 'The file 'filename' already exists.'

这是代码

File.WriteAllBytes(String_TempDir & "\rzip.zip", My.Resources.Resszip) 'I wrote the file from my application resources
Compression.ZipFile.ExtractToDirectory(String_TempDir & "\rzip.zip", String_TempDir) 'This line throws the exception
File.Delete(String_TempDir & "\rzip.zip")

在该代码执行之前我什么也没看到(没有文件)...

代码执行后,抛出异常,但是,我的归档文件已被提取。

我使用了 Try 语句来区分异常,但它仍然抛出该异常...

Try
    Compression.ZipFile.ExtractToDirectory(String_TempDir & "\rzip.zip", String_TempDir)
Catch ex As IOException
    'That's it.
End Try

String_TempDir 是一个字符串,我用它来赋值:

'global declaration:
Dim folder As String = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)
'End of global declaration

Public Function GetTempDir() As String

    Do While Directory.Exists(folder) Or File.Exists(folder)

        folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)

    Loop

    Return folder

End Function

'Form loads
Directory.CreateDirectory(folder)
String_TempDir = folder

只是猜测,但可能是您将 Zip 文件放入了您要解压到的同一目录中。尝试解压缩到临时目录的子目录。例如

Compression.ZipFile.ExtractToDirectory(String_TempDir & "\rzip.zip", String_TempDir & "\extracted")

MSDN article on ExtractToDirectory 说了以下内容(强调我的):

This method creates the specified directory and all subdirectories. The destination directory cannot already exist. Exceptions related to validating the paths in the destinationDirectoryName or sourceArchiveFileName parameters are thrown before extraction. Otherwise, if an error occurs during extraction, the archive remains partially extracted. Each extracted file has the same relative path to the directory specified by destinationDirectoryName as its source entry has to the root of the archive.

您是否还检查过 Zip 文件不包含任何重名? 如果它是在 Linux 上压缩的,它可能同时包含 Filenamefilename,这可能会导致此错误。尤其是你说一开始没有任何文件,貌似解压成功了

有些类似的问题 here,但使用 7-Zip