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

16,161

Solution 1

You can use this code:

public ActionResult Log()
{
    var fileContents = System.IO.File.ReadAllText(Server.MapPath("~/Views/Builder/TestLogger.txt"));
    return Content(fileContents);
}

Solution 2

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

Solution 3

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

Share:
16,161
user2624970
Author by

user2624970

Updated on July 14, 2022

Comments

  • user2624970
    user2624970 almost 2 years

    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.