如何在mvc中导出文本文件

本文关键字:文本 文件 mvc | 更新日期: 2023-09-27 18:08:45

我在代码中使用mvc格式的流编写器生成文本文件。但是我的文本文件没有下载到我的页面吗?我的示例代码如下:

//文件有流writerformat中所有的值

return File(file, "text/plain", "Export.txt");

如何在mvc中导出文本文件

尝试在返回前添加:

var cd = new System.Net.Mime.ContentDisposition
{
    FileName = "Export.txt", 
    Inline = false, 
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(file, "text/plain");

你可以像这样调用一个方法来给出你的文件流:

public FileStreamResult DownloadFile()
{
    //
    // This part is where you build your file
    //
    // file should be a Stream
    return new FileStreamResult(file, "text/plain")
        {
            FileDownloadName = "optional_name_that_you_can_give_your_file"
        };
}