Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Relative Path To File in Web.Config

I want to specify a path to a file in my application in the Web.Config file, then call that path in a controller. From what I've found online, I'm most of the way there.

Web.Config

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

Controller

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

However, this is pointing to the wrong location.

enter image description here

How can I point this to the file I have stored in the App_Data folder, starting from the root of my application?

like image 348
madvora Avatar asked Aug 26 '15 20:08

madvora


1 Answers

You can use Server.MapPath.

Or alternatively, store only the relative path in the configuration file, then use:

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

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

The latter technique will work in non-web applications, so is arguably better.

like image 197
Joe Avatar answered Oct 22 '22 18:10

Joe