asp. net gets an example of the absolute path to a website

  • 2020-11-18 06:09:43
  • OfStack


VirtualPathUtility.ToAbsolute( " ~/ " )
HttpRuntime.AppDomainAppVirtualPath
Request.ApplicationPath
Page.ResolveUrl( " ~ " )

The results generated by the above code are as follows:
When accessed as a web site, the results are as follows:


VirtualPathUtility.ToAbsolute("~/") = /
HttpRuntime.AppDomainAppVirtualPath = /
Request.ApplicationPath = /
Page.ResolveUrl("~") = /

When the virtual directory (http: / / localhost: 806 / web2 url aspx) access, the results are as follows:


VirtualPathUtility.ToAbsolute("~/") = /web2/
HttpRuntime.AppDomainAppVirtualPath = /web2
Request.ApplicationPath = /web2
Page.ResolveUrl("~") = /web2/

Using the second and third methods, also need to do 1 processing, because the site is visited with/end, and virtual directory access is no /, also have to make a judgment, a little trouble 1 point.
However, there is no problem with using these methods on the page, but if you want to get the absolute path of the site in the Application_Start event of Global, you need to use the first two methods, and if you use the third method, you will report the following error:
Request is not available in this context
Therefore, only the first two methods can be adopted. For example,


void Application_Start( object sender, EventArgs e)
{
    System.IO.StreamWriter s = new System.IO.StreamWriter(HttpRuntime.AppDomainAppPath + " log.txt " );
    s.WriteLine(VirtualPathUtility.ToAbsolute( " ~/ " ));
    s.WriteLine(HttpRuntime.AppDomainAppVirtualPath);
    s.Close();
}


Related articles: