How to specify a local file path for a user outside of a web application's directory?

527 views Asked by At

I am creating an ASP.NET MVC web application that serializes JSON files for user-inputed information. The base template that I was following operates like this:

string jsonData = JsonConvert.SerializeObject(rootObject);
string path = Server.MapPath("~/App_Data/");
System.IO.File.WriteAllText(path + ticket.TicketNumber + ".json", jsonData);
TempData["msg"] = " Json file Generated! Json files generated here can be found in *** ";
return RedirectToAction("Index");;

As I started to try to figure out how to add a method for the user to input where they would like to save their file locally (for an easy way for them to check in the file to TFS rather than moving the file from the app data folder to their desired folder) I realized that this only operates within the web app's directory. Is there something other than Server.MapPath(); that I can use to specify a location in a user's C:\ drive or not?

1

There are 1 answers

2
JuanR On BEST ANSWER

The code you provided only saves the file on the server, not the client.

If you want them to download the file and save it locally, you need to save the file on the server first (like you are already doing), making sure the file is saved under a publicly available folder and provide the user with a link on the view that they can click on to download the file.

The link will trigger the browser's download mechanism and pop a Save File dialog open so they can choose where they want to save the file.

There are other ways to implement a file download. Check out the File method of the Controller class for more details.