0

I have a asp.net c# web application. On one of the pages i have a button and when pressed I want it to create a text file with certain text and save it to the users PC. I do not want to save it on the server or anything.

I Currently have this which writes 'test' to a file:

string fileLoc = "filePath";
            FileStream fs = null;
            fs = File.Create(fileLoc);

            StreamWriter sw = new StreamWriter(fileLoc);
            sw.WriteLine("test");

            fs.Close();
            sw.Close();

How do I get it to save to the users computer.

Thanks for the help!.

Safinn
  • 622
  • 3
  • 15
  • 26
  • possible duplicate of [C# Asp.net write file to client](http://stackoverflow.com/questions/1072814/c-sharp-asp-net-write-file-to-client) – Tim Schmelter Nov 14 '13 at 15:33
  • 1
    related question: http://stackoverflow.com/questions/1008810/write-a-file-on-the-fly-to-the-client-with-c-sharp?tab=oldest – overloading Nov 14 '13 at 15:38
  • So there is no way of saving it to the PC without it popping up and asking them to save? I need to access some data on the page like a label text and use it in a vba macro which is local. – Safinn Nov 15 '13 at 07:44

3 Answers3

0

ASP.NET run on the server. If you would like to work with the client's computer you'll do it in Java Script. I recommend you to use any open source project written in javascript like this one https://github.com/eligrey/FileSaver.js.

Videron
  • 171
  • 1
  • 3
  • 11
0

You have to return it trough an action method.

public ActionResult DownloadFile(){
 return File(filePath, "text/plain", "MyFileName");
}

You cannot explicitly save it to the users PC because you simply don't have access to that. Returning it as an ActionResult (more specifically: FileResult) will return it as a download.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0

You can't save the file directly in the client. You must write it into a Response, and then send it back to the client as a Download. There's a lot of ways, one of those include write the file stream directly into the Response like:

Response.ContentType = "text/plain";
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.AddHeader("Content-Disposition", "attachment;filename=yourfile.txt");

Reference: C# Asp.net write file to client

Community
  • 1
  • 1
Fals
  • 6,813
  • 4
  • 23
  • 43