简体   繁体   中英

How Can I open the Text file in my MVC application?

I want to fetch the Text data from a Text file ::

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". I wat to know that How can I fetch the contents of this Text file in my "View" or "action" of MVC application.

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.

[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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM