[英]How Can I open the Text file in my MVC application?
I want to fetch the Text data from a Text file :: 我想从Text文件中获取Text数据::
For that, I have used code like :: 为此,我使用了像::
public ActionResult Log()
{
StreamReader reader = new StreamReader(Server.MapPath("~/Views/Builder/TestLogger.txt"));
return View(reader);
}
I have made this text file from "Log4Net". 我从“Log4Net”制作了这个文本文件。 I wat to know that How can I fetch the contents of this Text file in my "View" or "action" of MVC application. 我想知道如何在MVC应用程序的“视图”或“操作”中获取此文本文件的内容。
You can use this code: 您可以使用此代码:
public ActionResult Log()
{
var fileContents = System.IO.File.ReadAllText(Server.MapPath("~/Views/Builder/TestLogger.txt"));
return Content(fileContents);
}
You can use ContentResult
, it is used to return text content from Controller Actions. 您可以使用ContentResult
,它用于从Controller Actions返回文本内容。
[HttpGet]
public ActionResult Log() {
try {
string content = string.Empty;
using (var stream = new StreamReader(Server.MapPath("~/Views/Builder/TestLogger.txt"))) {
content = stream.ReadToEnd();
}
return Content(content);
}
catch (Exception ex) {
return Content("Something ");
}
}
Based on your comments to other answers, it would appear that the log file you're attempting to use is currently locked down by the server. 根据您对其他答案的评论,您尝试使用的日志文件目前似乎已被服务器锁定。 It's likely opening and writing to the log file because you've initiated a request that is getting logged, so you're blocking yourself from reading it. 它可能会打开并写入日志文件,因为您已经启动了一个记录的请求,因此您将阻止自己阅读它。
Assuming you're using a FileAppender
, setting appender.LockingModel = FileAppender.MinimalLock
when the logger is instantiated should allow the file to be accessed when nothing is being logged as opposed to the log4net process maintaining its lock while it is running. 假设您正在使用FileAppender
,在实例化记录器时设置appender.LockingModel = FileAppender.MinimalLock
应该允许在没有记录任何内容时访问该文件,而不是log4net进程在运行时保持其锁定。
This can also be set in the configuration if all the properties are set pre-runtime: 如果在运行前设置了所有属性,也可以在配置中设置:
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
You're not the first to have this issue: http://hoenes.blogspot.com/2006/08/displaying-log4net-log-file-on-aspnet.html 你不是第一个遇到这个问题的人: http : //hoenes.blogspot.com/2006/08/displaying-log4net-log-file-on-aspnet.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.