Reputation: 2532
I am creating a class to log errors in a .NET Web Forms application. However, because it is a separate class, I am having a lot of problems mapping to the correct path. Ordinarily I would use ~/, or /, but this does not work. I need it so that whatever Web Forms page calls the class, the application can find the appropriate file to write to. For example, as the code stands now, I get the following error:
$exception {"Could not find a part of the path 'C:\\Program Files (x86)\\IIS Express\\logs\\errors.txt'."} System.Exception {System.IO.DirectoryNotFoundException}
The class that does the logging:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace Ticket_System
{
public static class logger
{
const string PATH = "logs/errors.txt";
public static void logError(Exception ex) {
using (StreamWriter stream = File.AppendText(PATH))
{
stream.Write(ex.Source + " " + ex.Message + " " + ex.StackTrace + "/n/n");
}
}
}
}
How can I, within logger.cs, be able to reliably access the file (located in sub-directory, logs), regardless of what page calls it.
Thanks!
Upvotes: 1
Views: 2829
Reputation: 156708
You can use HttpRuntime.AppDomainAppPath
to get the path of your current website, or (if you know you'll always be calling this in the context of a Request) you can use HttpContext.Current.Server.MapPath("~")
.
However, I'd highly recommend that you use an existing logging framework rather than trying to roll your own. It'll save you a lot of headache in the long run.
Upvotes: 2