StackTrace
StackTrace

Reputation: 9416

How to change file extension when saving selected file in a FileUpload to the server

string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/ProcessedFiles/" + fileName));

The file am grabbing from FileUpload1 to save on the server is a .xls file (Excel 97-2003)

What i want is to save it with a .xlsx extension (Excel 2007 and above) on the server.

Upvotes: 1

Views: 2557

Answers (3)

James
James

Reputation: 167

You can retrieve the Filename without its original extension, and then append a new extension to it by using Path.GetFileNameWithoutExtension(String path), like so:

String filename = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName) + ".xlsx";
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/ProcessedFiles/" + filename));

On second thought, I totally forgot about ChangeExtension(), as @Matt has suggested. You should use his code.

Upvotes: 0

Habib
Habib

Reputation: 223267

You need to use Path.GetFileNameWithoutExtension method instead of Path.GetFileName

string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName) + "xlsx";
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/ProcessedFiles/" + fileName));

Upvotes: 0

Matt
Matt

Reputation: 6953

Use Path.ChangeExtension

string path = "C:\\SomePath\\Somefile.xls";
string newPath = Path.ChangeExtension(path, ".xlsx");

In your case, probably something like this (not tested):

string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
fileName = Server.MapPath(Path.Combine("~/ProcessedFiles/", fileName));
FileUpload1.PostedFile.SaveAs(Path.ChangeExtension(fileName, ".xlsx"));

Upvotes: 2

Related Questions