javascript 如何在我的 MVC 应用程序中打开文本文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18355653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:36:39  来源:igfitidea点击:

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

c#javascriptjqueryasp.net-mvc

提问by user2624970

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.

我从“Log4Net”制作了这个文本文件。我想知道如何在 MVC 应用程序的“视图”或“操作”中获取此文本文件的内容。

回答by Sirwan Afifi

You can use this code:

您可以使用此代码:

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

回答by Satpal

You can use ContentResult, it is used to return text content from Controller Actions.

您可以使用ContentResult,它用于从控制器操作返回文本内容。

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

回答by jdeering

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