[ACCEPTED]-How to create file and return it via FileResult in ASP.NET MVC?-asp.net-mvc
Accepted answer
EDIT ( If you want the stream try this: )
public FileStreamResult GetFile()
{
string name = "me.txt";
FileInfo info = new FileInfo(name);
if (!info.Exists)
{
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("Hello, I am a new text file");
}
}
return File(info.OpenRead(), "text/plain");
}
You could try something like this..
public FilePathResult GetFile()
{
string name = "me.txt";
FileInfo info = new FileInfo(name);
if (!info.Exists)
{
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("Hello, I am a new text file");
}
}
return File(name, "text/plain");
}
0
Open the file to a StreamReader
, and pass the stream 1 as an argument to the FileResult:
public ActionResult GetFile()
{
var stream = new StreamReader("thefilepath.txt");
return File(stream.ReadToEnd(), "text/plain");
}
Another example of creating and downloading 3 file from ASP NET MVC application at once 2 but file content is created in memory (RAM) - on 1 the fly:
public ActionResult GetTextFile()
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] contentAsBytes = encoding.GetBytes("this is text content");
this.HttpContext.Response.ContentType = "text/plain";
this.HttpContext.Response.AddHeader("Content-Disposition", "filename=" + "text.txt");
this.HttpContext.Response.Buffer = true;
this.HttpContext.Response.Clear();
this.HttpContext.Response.OutputStream.Write(contentAsBytes, 0, contentAsBytes.Length);
this.HttpContext.Response.OutputStream.Flush();
this.HttpContext.Response.End();
return View();
}
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.