在Web.Config中的ASP.NET相对路径到文件是什么?

12

我想在Web.Config文件中指定应用程序中文件的路径,然后在控制器中调用该路径。

Web.Config

<appSettings>
    <add key="filePath" value= "~/App_Data/Physicians.xml" />
</appSettings>

控制器

//Path of the document       
string xmlData = ConfigurationManager.AppSettings["filePath"].ToString();

然而,这指向了错误的位置。

在此输入图像描述

我该如何将其指向存储在我的应用程序根目录下的 App_Data 文件夹中的文件?


我知道|DataDirectory|在连接字符串中可以使用。但是不确定在AppSettings中是否可行。 - JDPeckham
1个回答

28
你可以使用 Server.MapPath 方法。
或者,仅在配置文件中存储相对路径,然后使用:
<appSettings>
    <add key="filePath" value= "App_Data/Physicians.xml" />
</appSettings>

string relativePath = ConfigurationManager.AppSettings["filePath"];
string combinedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativePath)

后一种技术可以在非网络应用中使用,因此可以说它更好。


您能详细说明一下吗? 您的意思是我不需要修改 Web.Config 部分吗?您能写出在控制器中如何进行调用吗?我不明白我该如何使用您的 Path.Combine 示例,或者我是否应该将其全部替换。 - madvora
relativePath 是你在 Web.Config 中保存的部分。你需要从路径中去掉波浪号,然后进行一些操作,比如 var relativePath = ConfigurationManager.AppSettings["filePath"].ToString(),然后使用 Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativePath)。 - Dylan

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