Telerik RadAsyncUpload control - Rename multiple files names if already exist

1.3k views Asked by At

Telerik's RadAsyncUpload control is used upload files to a file system or a shared folder. If the file already exists, we need to append a counter value to the end of the file.

I've written logic to add an integer value named counter to the file name but this code fails if I choose multiple files:

 foreach (UploadedFile file in AsyncUpload1.UploadedFiles)
 {
     string targetFolder = AsyncUpload1.TargetFolder;
     string targetFileName = System.IO.Path.Combine(targetFolder,
         file.GetNameWithoutExtension() + counter.ToString() + file.GetExtension());

     while (System.IO.File.Exists(targetFileName))
     {
         counter++;
         targetFileName = System.IO.Path.Combine(targetFolder,
         file.GetNameWithoutExtension() + counter.ToString() + file.GetExtension());
     }
     file.SaveAs(targetFileName);
 }

I want to rename multiple files if they already exist in the file share.

1

There are 1 answers

0
Tony L. On BEST ANSWER

This answer is assuming you have this code in the AsyncUpload1_FileUploaded subroutine. I'm making that assumption because I was able to recreate your issue with the code in there.

If that is the case, this event fires for each uploaded file. When you select the file, it creates a temp file in \App_Data\RadUploadTemp. That file gets deleted after AsyncUpload1_FileUploaded fires when you have the TargetFolder property set (it is not deleted right away if this property is not set per this Telerik forum).

Your code is looping through each of the files but when the event fires for the 2nd file, the first one has already been deleted which causes the error.

There is no need to loop through each file since AsyncUpload1_FileUploaded fires for every file. Remove your For Each statement and declare/set file like so: Dim file As UploadedFile = e.File

protected void AsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
{
    int counter = 0;
    UploadedFile file = e.File; //Replace your For Each statement with this line
    string targetFolder = AsyncUpload1.TargetFolder;
    string targetFileName = System.IO.Path.Combine(targetFolder, file.GetNameWithoutExtension() + counter.ToString() + file.GetExtension());
    while (System.IO.File.Exists(targetFileName)) {
        counter += 1;
        targetFileName = System.IO.Path.Combine(targetFolder, file.GetNameWithoutExtension() + counter.ToString() + file.GetExtension());
    }
    file.SaveAs(targetFileName);
}