0

This is an uploading tool. I am trying to rename a file name if it is existed in the folder already. The plan is to add a number after the file name. For example, if the file name is Hello.doc, it will be saved as Hello2.doc.

The problem is, the file name & file type are always different. It can be Goodbye.pdf/capture.png. I am not sure how to insert the number in the correct place.

if (System.IO.File.Exists(savepath))
            {
                int counter = 2;
                while (System.IO.File.Exists(savepath))
                {
                    string newFileName = fileName + counter;
                    tempFileName = newFileName.Insert/replace //Not sure what to do here
                    savepath += tempFileName;
                    counter++;
                }
                FileUpload.SaveAs(savepath);
                lblUpload.Text = "A file with the same name already exists." + " Your file was saved as " + tempFileName;
            }

Does someone know? Thanks!

1 Answer 1

1

Please let me know if this is what you were looking for. Used StringBuilder to avoid creating new String objects after every concatenation.

String[] filepath = filename.split(".");
// filepath[0] -> filename
// filepath[1] -> extension

StringBuilder newFilename = new StringBuilder(filepath[0]);

// add number
newFilename.append(2);

// add period
newFilename.append(".");

// add extension
newFilename.append(filepath[1]);

return newFilename.toString();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.