How to get the root path of a site in C #?

In C # code, I need to write src for the image. Does anyone know how to get the root path of a site in C #? My folder structure is UI / Image. I found that when I use

string rootpath=Page.Request.ApplicationPath; 

If you run the application in a debugging model, it works. But if you run it by typing url directly, it will not show the image. Image property http: //image/turnon.bmp , which should be http: //localhost/image/turnon.bmp

Any idea?

+7
source share
4 answers

An MapPath way is to use MapPath with a wildcard ~ :

 string imagePath = MapPath("~/image/turnon.bmp"); 

As Dan Csharpster stated in the comments, since the Server object that the MapPath method MapPath is not directly accessible in the class library, the command should be

 string imagePath = HttpContext.Current.Server.MapPath("~/image/turnon.bmp"); 
+17
source

Simple use sign.

since ~ represents the root of your application.

so your url will be

 <img src='<%= Server.MapPath("~/images/1.jpg") ' /> 
+3
source

If you are not using the mvc / web forms context, use VirtualPathUtility: http://msdn.microsoft.com/en-AU/library/system.web.virtualpathutility.toapprelative.aspx

 var siteRoot = VirtualPathUtility.ToAppRelative("~"); 
+3
source

I had the same problem when I used ASP.NET MVC2. you can use this:

 ResolveClientUrl("~/Content/Icons/loading1.gif") or Url.Resolve() 
+1
source

All Articles