My project is a Sharepoint Web-App, and it will generate a text file for the user and offer it for the user to download.
The web-app generates a string value and should use FileStream
to create a text file out of it. The user clicks a button and they should get a save-as dialogue.
Now, it is simple enough to use FileStream to write to the user's local drive, but how do you prompt them for the location and THEN save it there?
There are lots of questions about how to write to the local disk, and there are questions about how to open the save-dialogue in the browser. But I have not found any that answer the question of using the two methods together.
To write the file, we can use this:
using (var fs = new FileStream(@"C:\test.txt", FileMode.Create, FileAccess.ReadWrite)) {
TextWriter tw = new StreamWriter(fs);
tw.Write("Hello World");
tw.Flush();
}
and to open the save-as dialog, we can do this, which will tell the browser a file is ready for downloading which will open the browser's own save dialogue:
if (resp.IsClientConnected) {
resp.Clear();
resp.ClearHeaders();
//Indicate the type of data being sent
resp.ContentType = "text/plain"; //".htm", "html" = "text/html"
resp.AppendHeader("Content-Disposition", "attachment; filename=\"" + Path.GetFileName(gentextfilename) + "\"");
resp.AppendHeader("Content-Length", reader.BaseStream.Length.ToString());
resp.TransmitFile(file_name); //does not buffer into memory, therefore scales better for large files and heavy usage
resp.End();
}
Now, is there a way to combine these? I don't want to save the file to the server and then download it. I want to save it directly to a save location specified by the user. And to make all of this worse, it's a Sharepoint web-app, so it will run inside of Sharepoint, so I don't think you can use the folderBrowserDialog1
or SaveFileDialog
method like you can in a desktop application.
Summary of What Answer is Being Sought:
How can I create a file (without creating one on the server) to save to download location of the user's choice?