Here's how you can create a file in memory and then return it via an mvc action
public ActionResult DownLoadFile(){
MemoryStream memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);
tw.WriteLine("Hello World");
tw.Flush();
tw.Close();
return File(memoryStream.GetBuffer(), "text/plain", "file.txt");
}
In your browser if you go to /home/DownloadFile (assuming you put the action in the home controller). Then you should get a file download for a file called file.txt with "Hello world as the content"
SamU
Contributor
2895 Points
1627 Posts
How do I create and return a simple text file?
May 01, 2012 07:06 PM|LINK
Hi,
I have a string that I want to return as a simple text file. How do I do this in my MVC app?
P.S. I don't even need to save this file to disk. It won't be large so the easiest and most efficient approach would be preferable.
Sam
Bimalvv
Contributor
2356 Points
478 Posts
Re: How do I create and return a simple text file?
May 01, 2012 07:49 PM|LINK
Try this http://www.csharphelp.com/2005/12/simple-text-file-operations-in-c/
Bimal
CodeHobo
All-Star
18647 Points
2647 Posts
Re: How do I create and return a simple text file?
May 01, 2012 07:57 PM|LINK
Here's how you can create a file in memory and then return it via an mvc action
public ActionResult DownLoadFile(){ MemoryStream memoryStream = new MemoryStream(); TextWriter tw = new StreamWriter(memoryStream); tw.WriteLine("Hello World"); tw.Flush(); tw.Close(); return File(memoryStream.GetBuffer(), "text/plain", "file.txt"); }In your browser if you go to /home/DownloadFile (assuming you put the action in the home controller). Then you should get a file download for a file called file.txt with "Hello world as the content"
Blog | Twitter : @Hattan
SamU
Contributor
2895 Points
1627 Posts
Re: How do I create and return a simple text file?
May 01, 2012 08:01 PM|LINK
Thank you very much. I didn't realize I could use ActionResult. I thought I had to use FileStreamResult or FilePathResult.
Sam
CodeHobo
All-Star
18647 Points
2647 Posts
Re: How do I create and return a simple text file?
May 01, 2012 08:03 PM|LINK
No problem. ActionResult is the base class for both FilePathResult and FileStreamResult so it works with most mvc return types.
Blog | Twitter : @Hattan