如何创建文件并通过ASP.NET MVC中的FileResult返回它?

Ant*_*nte 21 asp.net-mvc

我必须在我的aplication ASP.net MVC应用程序中创建并返回文件.文件类型应该是普通的.txt文件.我知道我可以返回FileResult,但我不知道如何使用它.

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");
}
Run Code Online (Sandbox Code Playgroud)

此代码不起作用.为什么?如何使用流结果?

Big*_*ing 35

编辑(如果你想要流试试这个:)

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

}
Run Code Online (Sandbox Code Playgroud)

你可以试试这样的东西..

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

}
Run Code Online (Sandbox Code Playgroud)

  • 还要考虑其他选项 - http://stackoverflow.com/questions/1187261/whats-the-difference-between-the-four-file-results-in-asp-net-mvc记住该文件(可以容纳所有这些文件) . (3认同)
  • 在第二个示例中,您必须将声明名称变量替换为文件路径。字符串名称= Server.MapPath(“ / me.txt”); (2认同)

Tom*_*han 8

将文件打开为a StreamReader,并将该流作为参数传递给FileResult:

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