12

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?

1
  • I know |DataDirectory| works in the connection string. Not sure in AppSettings. Commented May 24, 2018 at 0:46

1 Answer 1

28

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Would you mind elaborating on this a little more? Are you saying that I leave the Web.Config portion alone? Can you write out how you would make this call in the controller? I don't see how I would use your Path.Combine example with what I have, or if I'm supposed to replace all of that.
relativePath would be the part which you store in your Web.Config. You would remove the tilda from your path and then go something like var relativePath = ConfigurationManager.AppSettings["filePath"].ToString() and then use Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativePath)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.