Как создать файл и вернуть его через FileResult в ASP.NET MVC?
Мне нужно создать и вернуть файл в моем приложении 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");
}
Этот код не работает. Зачем? Как это сделать с результатом потока?
Ответы
Ответ 1
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");
}
Вы можете попробовать что-то вроде этого.
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");
}
Ответ 2
Откройте файл StreamReader
и передайте поток в качестве аргумента в FileResult:
public ActionResult GetFile()
{
var stream = new StreamReader("thefilepath.txt");
return File(stream.ReadToEnd(), "text/plain");
}
Ответ 3
Еще один пример создания и загрузки файла из приложения ASP NET MVC сразу, но содержимое файла создается в памяти (ОЗУ) - на лету:
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();
}