Rename Files during Extraction (Zip) process ASP.Net

1.8k Views Asked by At

i have a RadUpload that uploads zip file only, so i want to rename the each file during Extraction Process, i tried a way :

Protected Sub Upload(sender As Object, e As EventArgs)

    Dim extractPath As String = Server.MapPath("~/temp/")
    Dim file1 As String = RadUpload1.UploadedFiles(0).FileName

    ExtractFileToDirectory(file1, extractPath)

End Sub

Public Sub ExtractFileToDirectory(zipFileName As String, outputDirectory As String)

    Dim zip As ZipFile = ZipFile.Read(outputDirectory & zipFileName)
    Directory.CreateDirectory(outputDirectory)
    For Each e As ZipEntry In zip

        Dim NewName As String = Now().ToString("ddMMyyhhmmss")
        Dim newext As String = ".jpg"
        e.FileName = NewName + newext

        e.Extract(outputDirectory, ExtractExistingFileAction.OverwriteSilently)
    Next
End Sub

at the first it will rename and extract the first file but then gives this error:

[ It has been adjusted Group: Could not execute the census process. ]

any idea?

2

There are 2 best solutions below

5
user2316116 On BEST ANSWER

It seems there is a problem with outputDirectory

Dim zip As ZipFile = ZipFile.Read(outputDirectory & zipFileName)
Directory.CreateDirectory(outputDirectory)

In the first line you are trying to read outputDirectory & zipFileName, in the second line you are trying to create that path.

See MSDN, your code should be similar to

Using zip As ZipArchive = ZipFile.OpenRead(zipFileName)
   For Each e As ZipArchiveEntry In zip.Entries

     Dim NewName As String = Now().ToString("ddMMyyhhmmss")
     Dim newext As String = ".jpg"
     NewName += newext
     e.ExtractToFile(Path.Combine(outputDirectory, NewName ))

   Next
 End Using

NOTE: Using "ddMMyyhhmmss" as a file name you most likely will get an error if unzip takes less than 1 sec - either add ms, i.e. "ddMMyyhhmmssfff" or check if file name does not exist before extract.

2
Matteo Marciano - MSCP On

Since you are expecting to extract to a "temp" folder, you really should be using the System temporary folder. Writing data inside your web app is a bad practice.

Use the following to retrieve the system-defined temporary folder

Private Sub Upload(sender As Object, e As EventArgs)

Dim extractPath As String = System.IO.Path.GetTempPath() ' Better way to store temporary files
Dim file1 As String = RadUpload1.UploadedFiles(0).FileName

ExtractFileToDirectory(file1, extractPath)

End Sub

Then inside ExtractFileToDirectory function you create a brand new temporary folder (use Guid.NewGuid().ToString() to generate a unique folder name) and unzip files as explained by @2316116, using the ExtractToFile method.

Following this approach saves you from nasty errors occurring when multiple zip files are unpacking at the very same time.