Question

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

Was it helpful?

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

OTHER TIPS

Do not save the uploaded files under the same name as the user provided. You will get many users uploading duplicated names. Generate a new name for each uploaded file and keep the original name in a database and keep a pointer to the generated file in the database. If a file is requested, do a lookup in the database to find the original file.

use File.Exist or use linq to get the file count and change fileName to reflect the new name.

Below code should do it.

public string CalculateNextFileName(string filename, string dir)
{
   var file = Path.GetFileNameWithoutExtension(filename);
   var files = new DirectoryInfo(@"M:\testdir").GetFiles(file + "*");
   return string.Format("{0} ({1})",file, files.Count ());
}

Usage:

var newFileName = "New Text Document.txt";

var nextFileName = CalculateNextFileName(newFileName, "C:\testdir");

This is a very naive implementation that doesn't take account of missing files in the sequence (ie. if files 2 and 3 were missing, this would pump out the name of a potentially existing file).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top