在MVC3 Razor中显示文本文件的内容 [英] Display contents of Text File in MVC3 Razor

查看:159
本文介绍了在MVC3 Razor中显示文本文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我不知道如何继续查看。



请告诉我们。

解决方案

Content 代替,它会呈现你直接放入响应流的所有内容,响应类型为 text / plain



然后你甚至不需要一个View。



另外不要忘记处理你的资源和异常处理。您不希望在返回调用中放置 stream.ReadToEnd()



像这样做:

$ p $ [HttpGet]
public ActionResult ShowFile(){
string filepath = Server.MapPath( \\一些unc路径\\TextFile1.txt);
string content = string.Empty;

尝试{
using(var stream = new StreamReader(filepath)){
content = stream.ReadToEnd();


catch(Exception exc){
return Content(呃oh!);
}

返回内容(content);
}


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.

解决方案

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

这篇关于在MVC3 Razor中显示文本文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆