Get application path without using httpcontext. (asp.net)
Asked Answered
O

3

52

How to do it?

I don't want to use this:

HttpContext.Current.Server.MapPath

Is there a similar function that I can call without requiring a httpcontext?

For example if a start a thread doing some stuff i cant use the httpcontext, but i still need to get the path of the app. And no i can't pass the context as an argument or read it from a shared var.

Osis answered 9/3, 2010 at 14:6 Comment(0)
T
75

Use the HttpRuntime.AppDomainAppPath property.

Tinware answered 9/3, 2010 at 14:8 Comment(1)
It's a low-level class that most people don't need to use.Tinware
H
62

There are several options:

HttpRuntime.AppDomainAppPath

    WebApplication     -> Web root folder
    UnitTest           -> ArgumentNullException
    ConsoleApplication -> ArgumentNullException

AppDomain.CurrentDomain.BaseDirectory

    WebApplication     -> Web root folder
    UnitTest           -> ...\AppDir\bin\Debug
    ConsoleApplication -> ...\AppDir\bin\Debug

HostingEnvironment.ApplicationPhysicalPath

    WebApplication     -> Web root folder
    UnitTest           -> null
    ConsoleApplication -> null

I would recommend to use AppDomain.CurrentDomain.BaseDirectory, because it can be used in any type of project and it can be set up.

You can for example set UnitTest BaseDirectory to point your web root folder the AppDomain.CurrentDomain.BaseDirectory by command:

AppDomain.CurrentDomain.SetData("APPBASE", "path to your web root");
Hydrolytic answered 1/3, 2014 at 22:15 Comment(0)
A
1

I have run across this question when looking for way to compute an URL (permalinks in the Web application) to provide in some e-mail notifications.

These were generated on another thread, so HttpContext was not available and I wanted to avoid putting URL related information in the queue table used to generate the e-mails.

The code:

public static String GetCurrentAppDomainBasePath(String prefix = "http://")
{
   return String.Format("{0}{1}{2}", 
      prefix,
      System.Net.Dns.GetHostEntry("").HostName, 
      System.Web.HttpRuntime.AppDomainAppVirtualPath
   );
}

The function returns the full virtual path like: http://full-host-name/AppName. Of course, there are some limitations: hardcoded protocol (http, https etc.) and using hostname instead of domain name (fails if multiple domains are defined on a single machine).

Annmaria answered 18/3, 2016 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.