C#类库:StreamWriter写入system32文件夹

时间:2010-09-29 19:18:00

标签: c# logging class-library error-logging streamwriter

我有一个类库,它部署在ISP服务器上,供ASP.NET Web服务使用。我想跟踪任何错误,在这种情况下,我无法访问Windows事件日志。所以我以为我会使用StreamWriter类写入txt文件。问题是,如果我不给出绝对路径,只是尝试写入C:\ Windows \ System32的文件名,这对我没有好处。 如何告诉它使用数据目录或应用程序根目录?有什么想法吗?

5 个答案:

答案 0 :(得分:3)

使用Server.MapPath获取相对于Web应用程序的路径。

using (FileStream fs = new FileStream(Server.MapPath("~/logs/logfile.txt"),
                                      FileMode.Append)) {
  //do logging here.
}

虽然之前的一些海报已经建议使用反射来获取正在执行的程序集,但我不确定这是否会使您获得Web应用程序或w3wp进程。如果是后者,你仍然会尝试写入System32文件夹。

答案 1 :(得分:2)

这是我以前使用的,它有点笨重,但它完成了工作:

using System;
using System.Collections.Generic;
using System.Web.UI;

public static class Logger
{
private static readonly Page Pge = new Page();
        private static readonly string Path = Pge.Server.MapPath("~/yourLogPath/Log.txt");
        private const string LineBreaker = "\r\n\r======================================================================================= \r\n\r";

public static void LogError(string myMessage, Exception e)
{
    const LogSeverity severity = LogSeverity.Error;
    string messageToWrite = string.Format("{0} {1}: {2} \r\n\r {3}\r\n\r {4}{5}", DateTime.Now, severity, myMessage, e.Message, e.StackTrace, LineBreaker);
    System.IO.File.AppendAllText(Path, messageToWrite);
}
}

我在自己的项目中有这个课程,与网站本身分开,我在所有其他非网站项目中使用它......

编辑: Btw LogSeverity只是我编造的一个枚举......

答案 2 :(得分:1)

在我的网络产品中,在web.config中我指定了一个appSettings块,如下所示:

<configuration>
    <appSettings>
      <add key="MyLogPath" value="LogPath" />
    </appSettings>
</configuration>

您可以从

等代码中使用
ConfigurationManager.AppSettings["MyLogPath"]

然后您可以让安装程序将其配置到您想要的任何位置。您可能不希望应用程序目录中的日志文件。

答案 3 :(得分:0)

尝试退房:

Application.StartupPath;

这是link to the docs

  

获取可执行文件的路径   这启动了应用程序,而不是   包括可执行文件名。

string path = Application.StartupPath;

注意:您仍然需要添加文件名。

答案 4 :(得分:0)

您可以通过以下方式找到可执行文件的路径:

string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);