Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create file and return it via FileResult in ASP.NET MVC?

Tags:

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?

like image 283
Ante Avatar asked Sep 03 '09 19:09

Ante


People also ask

How do I return FileStreamResult?

return File(streamreader. ReadToEnd(), "text/plain", "Result. PDF"); You do not need to change the return type of the action as FilePathResult inherits from ActionResult, so in the case of an error you can return the view to handle this.

What is ActionResult return type in MVC?

An ActionResult is a return type of a controller method in MVC. Action methods help us to return models to views, file streams, and also redirect to another controller's Action method.


1 Answers

EDIT ( If you want the stream try this: )

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");  } 
like image 91
BigBlondeViking Avatar answered Sep 29 '22 10:09

BigBlondeViking