Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在c#中获取网站根路径?_C# - Fatal编程技术网

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

如何在c#中获取网站根路径?,c#,C#,在c代码中,我需要为图像编写src。有人知道如何在c#中获取网站根路径吗?我的文件夹结构是UI/Image 我发现当我使用 string rootpath=Page.Request.ApplicationPath; 如果在调试模型中运行该应用程序,它将正常工作。但若直接键入url来运行它,它将不会显示图像。图像的属性是应该显示哪个 有什么想法吗?一个简单的方法是使用MapPath和~通配符: string imagePath = MapPath("~/image/turnon.bmp");

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

string rootpath=Page.Request.ApplicationPath;
如果在调试模型中运行该应用程序,它将正常工作。但若直接键入url来运行它,它将不会显示图像。图像的属性是应该显示哪个


有什么想法吗?

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

string imagePath = MapPath("~/image/turnon.bmp");
与注释中一样,由于暴露
MapPath
方法的
Server
对象在类库中不直接可用,因此命令应为

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

我在使用ASP.NET MVC2时也遇到了同样的问题。您可以使用以下选项:

ResolveClientUrl("~/Content/Icons/loading1.gif")
or  Url.Resolve()
简单 使用~符号

因为~表示应用程序的根

因此,您的图像url将是

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

当您不在mvc/web表单上下文中时,请使用VirtualPath功能:


如果您所在的类不能自动访问HttpContext,可以这样调用它:var imagePath=HttpContext.Current.Server.MapPath(“~/someImage.jpg”);由于我对
Url
的所有搜索都返回了不相关的页面,在哪里可以找到
Url
ResolveClientUrl
var siteRoot = VirtualPathUtility.ToAppRelative("~");