Why AppDomain.CurrentDomain.BaseDirectory not contains “bin” in asp.net app?

后端 未结 4 780
天命终不由人
天命终不由人 2020-11-28 11:58

I have a web project like:

namespace Web
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, Event         


        
相关标签:
4条回答
  • 2020-11-28 12:25

    Per MSDN, an App Domain "Represents an application domain, which is an isolated environment where applications execute." When you think about an ASP.Net application the root where the app resides is not the bin folder. It is totally possible, and in some cases reasonable, to have no files in your bin folder, and possibly no bin folder at all. Since AppDomain.CurrentDomain refers to the same object regardless of whether you call the code from code behind or from a dll in the bin folder you will end up with the root path to the web site.

    When I've written code designed to run under both asp.net and windows apps usually I create a property that looks something like this:

    public static string GetBasePath()          
    {       
        if(System.Web.HttpContext.Current == null) return AppDomain.CurrentDomain.BaseDirectory; 
        else return Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"bin");
    } 
    

    Another (untested) option would be to use:

    public static string GetBasePath()          
    {       
        return System.Reflection.Assembly.GetExecutingAssembly().Location;
    } 
    
    0 讨论(0)
  • 2020-11-28 12:34

    If you use AppDomain.CurrentDomain.SetupInformation.PrivateBinPath instead of BaseDirectory, then you should get the correct path.

    0 讨论(0)
  • 2020-11-28 12:39

    In case you want a solution that works for WinForms and Web Apps

        public string ApplicationPath
        {
            get
            {
                if (String.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath))
                {
                    return AppDomain.CurrentDomain.BaseDirectory; //exe folder for WinForms, Consoles, Windows Services
                }
                else
                {
                    return AppDomain.CurrentDomain.RelativeSearchPath; //bin folder for Web Apps 
                }
            }
        }
    

    Above solution code snippet is for binaries locations

    The AppDomain.CurrentDomain.BaseDirectory is still valid path for Web Apps, it's just a root folder where the web.config and Global.asax and is same as Server.MapPath(@"~\");

    0 讨论(0)
  • 2020-11-28 12:42

    When ASP.net builds your site it outputs build assemblies in its special place for them. So getting path in that way is strange.

    For asp.net hosted applications you can use:

    string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml");
    
    0 讨论(0)
提交回复
热议问题