在MVC3 Razor中显示文本文件的内容

Vip*_*pul 3 file razor asp.net-mvc-3

我试图在视图中显示文本文件的内容.到目前为止,我已经能够为控制器获取以下代码:

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

我不知道如何继续这个观点.

好心提醒.

RPM*_*984 8

好吧,您可以return Content改为,它会将您放入响应流的任何内容呈现给响应流,其响应类型为text/plain.

那你甚至不需要View.

另外,不要忘记处理资源和异常处理.你不想把它stream.ReadToEnd()放在回电话中.

像这样做:

[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);
} 
Run Code Online (Sandbox Code Playgroud)