开发者

C# Class Library: StreamWriter writing to system32 folder

I have a class library which is deployed on an ISP server to be consumed by an ASP.NET web service. I'd like to keep track of any errors and in this case the windows event log is 开发者_开发百科inaccessible to me. So I thought I'd write to a txt file using the StreamWriter class. Problem is if I don't give an absolute path and just a file name it tries to write to C:\Windows\System32, and that's no good to me. How can I tell it to use maybe the data directory or the application root? Any thoughts?


Use Server.MapPath to get a path relative to the web application.

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

While some of the previous posters have suggested using reflection to get the executing assembly, I'm not sure whether or not that will net you the web application or the w3wp process. If it's the latter, you're still going to end up trying to write to the System32 folder.


Here is what I used to use, it's a little clunky but it gets the job done:

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

I had this class in it's own project, separate from the website itself, and I used it in all of my other non website projects...

Edit: Btw LogSeverity is just an enum I made up...


In my web product, in the web.config I specify an appSettings block like this:

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

which you can use from the code like

ConfigurationManager.AppSettings["MyLogPath"]

then you can have the installer configure it to wherever you want. you probably don't want the log files in your application directory.


Try checking out:

Application.StartupPath;

Here's a link to the docs

Gets the path for the executable file that started the application, not including the executable name.

string path = Application.StartupPath;

Note: you'll still need to add a file name.


You can find out the path of your executable by doing this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜