I want to extract archive. But the problem is, when the code runs, it throws the exception below:
System.IO.IOException: 'The file 'filename' already exists.'
Here are the code
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")
I saw nothing(no file) before that code executed...
After the code executed, It throws the exception, but, my archived file has been extracted.
I used Try statement to distinguish the exception but it's still throwing that exception...
Try
Compression.ZipFile.ExtractToDirectory(String_TempDir & "\rzip.zip", String_TempDir)
Catch ex As IOException
'That's it.
End Try
The String_TempDir is a string which I assign it with:
'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
Just guessing, but it could be that you are putting the Zip file into the same directory you are extracting to. Try extracting to a subdirectory of your temp directory. e.g.
Compression.ZipFile.ExtractToDirectory(String_TempDir & "\rzip.zip", String_TempDir & "\extracted")
The MSDN article on ExtractToDirectory says the following (emphasis mine):
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.