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?
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.
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.
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With