Search code examples
asp.netvb.netuploadserver.mappath

how to upload excel with duplicate name


how to upload excel file with duplicate name file but its don't do overwrite the previous name file. So if i upload the file with same name it will saving like windows do.

ex. firstly i upload excel file = "fileExcel". then i upload again with same name ="fileExcel". And it should be 2 file on the upload folder, first with name "fileExcel" and "fileExcel(1)".

so if i upload again and again with the same name of file it will continuously grow. (1),(2),(3),(4), etc

here is my code :

    Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
        Dim fileExtension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
        Dim fileLocation As String = Server.MapPath("~/Upload/" & fileName)
        FileUpload1.SaveAs(fileLocation)
 If fileExtension = ".xls" Then
            connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
        ElseIf fileExtension = ".xlsx" Then
            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
        End If

thanks before


Solution

  • You could use a File.Exists and a counter variable:

    Dim fileExtension = IO.Path.GetExtension(fileLocation)
    Dim fileName = IO.Path.GetFileNameWithoutExtension(fileLocation)
    Dim folder = IO.Path.GetDirectoryName(fileLocation)
    Dim counter = 0
    While IO.File.Exists(fileLocation)
        counter += 1
        Dim newFileName = String.Format("{0}({1}){2}", fileName, counter, fileExtension)
        fileLocation = IO.Path.Combine(folder, newFileName)
    End While