[ACCEPTED]-How to create file and return it via FileResult in ASP.NET MVC?-asp.net-mvc

Accepted answer
Score: 36

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

Score: 8

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");
}
Score: 2

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();
}

More Related questions