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

时间:2009-09-03 19:37:16

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

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

3 个答案:

答案 0 :(得分:34)

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

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

}

你可以尝试这样的事情......

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

}

答案 1 :(得分:8)

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

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

答案 2 :(得分:1)

另一个从ASP NET MVC应用程序创建和下载文件的例子,但文件内容是在内存(RAM)中创建的 - 即时:

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