Code Code - 26 days ago 5
ASP.NET (C#) Question

Using same method to download different file

I'm currently working on an web app which I'm using C# and Asp.Net MVC. On one of the page I have a requirement where users are able to download files and fill in the relevant data then upload them. Due to some users having old machine I'm working with

.xls
and
.xlsx
. Which file can be downloaded is based upon a dropdown value which a user must select.

I have two buttons one for
.xls
and one for
xlsx
file. My question is how can I use the same backend code to swap between the files. So if
.xls
is clicked the user gets the
.xls
file and if the other is click then they receive
.xlsx
file.

This is my code so far:

public FileResult DownloadTemplates(string policyType)
{
string templateName = string.Empty;
string baseDirectory = "base path";
string templateDirectory = "temnplate directory path";

switch (policyType)
{
case "Administrative":
templateName = "Admin Xls File"; //How can I swap between the .xls and .xlsx file?
break;
case "Policy":
templateName = "Policy Xls File"; //How can I swap between the .xls and .xlsx file?
break;
case "Consignment":
templateName = "Consignment Xls File"; //How can I swap between the .xls and .xlsx file?
break;
case "Quality":
templateName = "Quality Xls file"; //How can I swap between the .xls and .xlsx file?
break;
default:
templateName = string.Empty;
break;
}

string filePath = Path.Combine(baseDirectory, templateDirectory, templateName);
byte[] fileData = System.IO.File.ReadAllBytes(filePath);
string contentType = MimeMapping.GetMimeMapping(filePath);

return File(fileData, contentType);
}

Answer

There's a Path method - Path.ChangeExtension that will change the extension for you:

If path has no extension, and extension is not null, the returned path string contains extension appended to the end of path.

As this would also work if you stored the name of the file with one of the extensions already in place (e.g. xlsx) then all you'd need to do would be:

if (xlsSelected)
    Path.ChangeExtension(filePath, ".xlsx");

Obviously you'll need to pass in (or otherwise determine) xlsSelected.

Alternatively, if you just store the template name without the extension you can do:

if (xlsSelected)
    templateName = templateName + ".xls";
else
    templateName = templateName + ".xlsx";

You can go further by making the extension strings resources and/or configurable in case there's a need to change them again in the future.

Comments