简体   繁体   中英

Renaming the files is renaming the extension of the file

On My web site, I am letting the users upload the file and before saving the file on my server, I am renaming the file. If the user upload the file test.pdf, I want to rename the file test_123.pdf, but instead the file is renamed to test.pdf_123.pdf Below is my code:

foreach (HttpPostedFile uploadedFile1 in UploadPDF.PostedFiles)
                        {
                            if (Path.GetExtension(uploadedFile1.FileName) == ".pdf")
                            {
                            
                                 UploadedFile = UploadPath + uploadedFile1.FileName;
                                 RenamedFile = UploadPath + uploadedFile1.FileName + "_" +  applicationID + ".pdf";
                                 File.Move(UploadedFile, RenamedFile);
                            
                            }
                        }

applicationID is changing for every file.

With the above code, my renaming of the file is appended after the already existing file extension.

You need to remove the extension and take only the filename part before processing the change:

UploadedFile = UploadPath + uploadedFile1.FileName;
UploadedFileTemp = UploadPath + Path.GetFileNameWithoutExtension(uploadedFile1.FileName);
RenamedFile = UploadedFileTemp + "_" +  applicationID + ".pdf";

I think it is happening because of uploadedFile1.FileName . Before uploading, just remove the extension. There is one Trim function that might be useful.

Take a look at this link: .Net Trimming

I think you can use TrimEnd() function to remove the extension.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM