Is there a way to use Server.MapPath in a class in my asp.net application

I have a log.txt file in the root of my application. I would like my log class to be able to access this file and write to it. But I'm not sure how to tell it the correct file path in my code. Thanks for any help

using (StreamWriter w = File.AppendText("log.txt"))
    {
         Log(e.ToString(),w);
         w.Close();
    }

      

+3


source to share


2 answers


Using

Server.MapPath("~/log.txt")

      

to get the full filename.

Update:



If you are not on an ASP page, but in a regular class, try:

System.Web.HttpContext.Current.Server.MapPath("~/log.txt")

      

Update 2: It looks like you are trying to make your own registration solution. You can use an existing solution like NLog or Log4Net .

+13


source


Usually you will get this path from Web.config.
And it will be the physical path to the file, not the relative URL path. No need for MapPath.

The easiest way is to create it with the Designer tool and read it as



 string fname = Properties.Settings.Default.LogFile;

      

+1


source







All Articles