如何在c#中获取网站根路径?

Ste*_*ack 7 c#

在c#代码中,我需要为图像编写src.有谁知道如何在c#中获取网站根路径?我的文件夹结构是UI/Image我发现当我使用时

string rootpath=Page.Request.ApplicationPath;
Run Code Online (Sandbox Code Playgroud)

如果在调试模型中运行应用程序,它可以工作.但如果通过直接输入url来运行它,它将不会显示图像.图像的属性是http://image/turnon.bmp,它应该是http://localhost/image/turnon.bmp

任何的想法?

Eri*_*lli 18

一个简单的方法是使用MapPath~通配符:

string imagePath = MapPath("~/image/turnon.bmp");
Run Code Online (Sandbox Code Playgroud)

正如Dan Csharpster在评论中所说,由于Server暴露MapPath方法的对象不能直接在类库中使用,因此命令应该是

string imagePath = HttpContext.Current.Server.MapPath("~/image/turnon.bmp");
Run Code Online (Sandbox Code Playgroud)

  • 如果你在一个不能自动访问HttpContext的类中,你可以像这样调用它:var imagePath = HttpContext.Current.Server.MapPath("〜/ someImage.jpg"); (9认同)