0

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?

C Murphy
  • 47
  • 1
  • 13
  • You do realize that the file you are generating is being saved on the **server**, not the client computer, right? – JuanR Oct 12 '18 at 14:38
  • Yes, I know. I was only concerned initially if the serialized Json file was formatted correctly. Now I am concerned with finding a way to have it saved on the client's computer (based on whatever file path they specify). Assuming that is even possible... – C Murphy Oct 12 '18 at 14:41

1 Answers1

0

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.

JuanR
  • 7,405
  • 1
  • 19
  • 30
  • Thank you @JuanR for the timely and helpful response, but do I need a save as dialog in order to accomplish this, or is there a way to have it automatically download based on the user-entered location? – C Murphy Oct 12 '18 at 14:49
  • @CMurphy: I added a comment after I posted the original answer. There are other ways to stream the file directly. Check out the note about the `File` method. – JuanR Oct 12 '18 at 15:32