How to create file and return it via FileResult in ASP.NET MVC?

Solution 1:

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");

}

Solution 2:

Open the file to a StreamReader, and pass the stream as an argument to the FileResult:

public ActionResult GetFile()
{
    var stream = new StreamReader("thefilepath.txt");
    return File(stream.ReadToEnd(), "text/plain");
}

Solution 3:

Another example of creating and downloading file from ASP NET MVC application at once but file content is created in memory (RAM) - on 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();
}