在MVC3 Razor中显示文本文件的内容 [英] Display contents of Text File in 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屋!