how to get website root path in c#?
In c# code, I need to write src for an image. Does anyone know how to get webs开发者_运维百科ite root path in c#? My folder structure is UI/Image I found that when I use
string rootpath=Page.Request.ApplicationPath;
If run the application in debug model, it works. But if run it by typing url directly, it won't show image. The property of the image is http://image/turnon.bmp which should be http://localhost/image/turnon.bmp
Any idea?
An easy way is use MapPath
with the ~
wildcard:
string imagePath = MapPath("~/image/turnon.bmp");
As Dan Csharpster stated in the comments, since the Server
object which exposes the MapPath
method is not directly available in a class library the command should be
string imagePath = HttpContext.Current.Server.MapPath("~/image/turnon.bmp");
Simple use the ~ sign
as the ~ represents the root of your app.
so yourimage url will be
<img src='<%= Server.MapPath("~/images/1.jpg") ' />
i had the same problem when I was using ASP.NET MVC2. you can use this:
ResolveClientUrl("~/Content/Icons/loading1.gif")
or Url.Resolve()
When you are not in a mvc / web forms context use VirtualPathUtility: http://msdn.microsoft.com/en-AU/library/system.web.virtualpathutility.toapprelative.aspx
var siteRoot = VirtualPathUtility.ToAppRelative("~");
This is for the root of the virtual path not the physical directory of the website on the server In a c# MVC 5 controller this works for me.
string siteRoot = System.Web.VirtualPathUtility.ToAbsolute("~");
精彩评论