22

I have to create and return file in my aplication ASP.net MVC aplication. The file type should be normal .txt file. I know that i can return FileResult but i don't know how to use it.

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

This code doesn't work. Why? How to do it with stream result?

Ante
  • 8,567
  • 17
  • 58
  • 70

3 Answers3

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

}
BigBlondeViking
  • 3,853
  • 1
  • 32
  • 28
  • 3
    Also consider the other options- http://stackoverflow.com/questions/1187261/whats-the-difference-between-the-four-file-results-in-asp-net-mvc remembering that File( can accomodate all of them. – RichardOD Sep 03 '09 at 20:31
  • Yea, the File([params],...) will do what you want...you need to figure out what u want... – BigBlondeViking Sep 04 '09 at 13:05
  • 2
    In the second example you must replace declaring name variable to file path. string name = Server.MapPath("/me.txt"); – Cheburek Oct 22 '11 at 22:17
8

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");
}
Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
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();
}
Bronek
  • 10,722
  • 2
  • 45
  • 46