开发者

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 Fi开发者_如何学Gole(stream.ReadToEnd(), "text/plain");      
} 

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

Kindly advise.


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);
} 


Return Content(yourText) not a file result. That is for file downloads. If you want to set it in a view with other data as well then create a viewmodel class and assign your text to a property in the model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜