【问题标题】:How to create file and return it via FileResult in ASP.NET MVC?如何在 ASP.NET MVC 中创建文件并通过 FileResult 返回它?
【发布时间】:2009-09-03 19:37:16
【问题描述】:

我必须在我的应用程序 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");
}

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

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

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

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

    【讨论】:

    • 还要考虑其他选项 - stackoverflow.com/questions/1187261/… 记住 File( 可以容纳所有这些选项。
    • 是的,File([params],...) 会做你想做的......你需要弄清楚你想要什么......
    • 在第二个示例中,您必须将声明名称变量替换为文件路径。字符串名称 = Server.MapPath("/me.txt");
    【解决方案2】:

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

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

    【讨论】:

    • 请注意,"thefilepath.txt" 需要是文本文件的完整路径,而不仅仅是相对路径。
    • 如何创建一个?使用“TextWriter tw = new StreamWriter("date.txt");”还是别的什么?
    • 是的,例如像这样。请记住,文件路径必须是完整路径,并使用using 语句。
    【解决方案3】:

    另一个同时从 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 2013-10-08
      相关资源
      最近更新 更多