如何在 ASP.NET MVC 中创建文件并通过 FileResult 返回它? [英] How to create file and return it via FileResult in ASP.NET MVC?
本文介绍了如何在 ASP.NET MVC 中创建文件并通过 FileResult 返回它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须在我的应用程序 ASP.net MVC 应用程序中创建并返回文件.文件类型应该是普通的 .txt 文件.我知道我可以返回 FileResult 但我不知道如何使用它.
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?
推荐答案
EDIT(如果你想要流试试这个:)
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");
}
这篇关于如何在 ASP.NET MVC 中创建文件并通过 FileResult 返回它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文