Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display contents of Text File in MVC3 Razor

I am trying to display contents of a text file in a view. So far I have been able to get the following code for the controller:

public ActionResult ShowFile()     
{         
     string filepath = Server.MapPath("\\some unc path\\TextFile1.txt");
     var stream = new StreamReader(filepath);         
     return File(stream.ReadToEnd(), "text/plain");      
} 

I do not know how to go ahead with the view.

Kindly advise.

like image 292
Vipul Avatar asked Dec 30 '25 11:12

Vipul


1 Answers

Well, you could return Content instead, and it will render whatever you put in directly to the response stream, with the response type of text/plain.

Then you don't even need a View.

Also don't forget about disposing of your resources and exception handling. You don't want to put the stream.ReadToEnd() in the return call.

Do it like this:

[HttpGet]
public ActionResult ShowFile() {         
     string filepath = Server.MapPath("\\some unc path\\TextFile1.txt");
     string content = string.Empty;

     try {
        using (var stream = new StreamReader(filepath)) {
          content = stream.ReadToEnd();
        }
     }
     catch (Exception exc) {
       return Content("Uh oh!");
     } 

     return Content(content);
} 
like image 51
RPM1984 Avatar answered Jan 03 '26 14:01

RPM1984



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!