tags:

views:

1016

answers:

2

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?

+1  A: 

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 Lycken
Note that `"thefilepath.txt"` needs to be the full path to the text file, not just a relative path.
Tomas Lycken
how can i create one? with "TextWriter tw = new StreamWriter("date.txt");" or something else?
Ante B.
Yes, for example like so. Remember that the file paths need to be full paths, and use `using` statements.
Tomas Lycken
+3  A: 

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
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
this do not work so i uncked the "nike" sign
Ante B.
Yea, the File([params],...) will do what you want...you need to figure out what u want...
BigBlondeViking