如何在ASP.NET中获取应用程序路径?

39

如何获取应用程序路径?bin路径

在ASP.NET中

提前感谢


相关帖子请点击此处 - RBT
另一篇讨论在 .Net 中的 Web 应用程序中的服务器映射路径的帖子:https://dev59.com/v3VC5IYBdhLWcg3wfxM8 - RBT
7个回答

40

3
如果您没有请求可用,就像我刚才所做的那样,请使用此选项。很好的答案。 - allen1

30

20

我在app_start时需要它,那里还没有HttpContext,因此RequestServer都不是可选项。

这个方法解决了我的问题:

System.Web.HttpRuntime.BinDirectory

编辑

.net core开始,您可以使用nuget包Microsoft.Extensions.PlatformAbstractions中的PlatformServices.Default.Application.ApplicationBasePath,它会为任何运行时解析。


16
HttpContext.Current.Server.MapPath("~/bin") ;
Application.StartupPath + "/bin";
AppDomain.CurrentDomain.BaseDirectory + "/bin";

//Note in Asp.net Core its little bit different
public class ValuesController : ControllerBase
{
        IHostingEnvironment _hostingEnvironment;
        public ValuesController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
            string applicationPath = _hostingEnvironment.ContentRootPath;
            string wwwrootPath = _hostingEnvironment.WebRootPath;
        }
}

还有许多其他内容在这个博客中有描述。


这是我在WebApi请求中唯一有效使用的答案。谢谢。 - iCollect.it Ltd

13

使用以下代码片段:

string strPath = HttpContext.Current.Server.MapPath("~/bin");

4
Server.MapPath("~/bin")

您还可以使用Request.PhysicalApplicationPath


2

HostingEnvironment.MapPath()Server.MapPath()的区别:Server.MapPath用于将ASP.NET中的物理位置映射到Web服务器上。 String path = HttpContext.Current.Server.MapPath("~/myFolder/myFile.txt"); Server.MapPath指定要映射到物理目录的相对或虚拟路径。

示例:


 string path=System.Web.Hosting.HostingEnvironment.MapPath(@"~/Files/ExamResult.rdlc");

更多细节请访问此链接

最初的回答是:


1
请在您的答案中加入一些解释,以便他人能够学习。 - Nico Haase

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接