jordanchase
jordanchase

Reputation: 86

How can I set a relative path in App.Config?

I'm working on WPF C# ans I'm using Visual Studio 2017.

It is to set the file path of appSettings. I want to define a relative path in App.Config file. If I try with absolute path it works.

This work:

<appSettings file="C:\Users\jordan\AppData\Roaming\Test\appfile.config">

But if I try with relative path it does not work.

This does not work:

<appSettings file="${AppData}\Roaming\Test\appfile.config">

<appSettings file="~\AppData\Roaming\Test\appfile.config">

<appSettings file="~/AppData/Roaming/Test/appfile.config">

etc...

Do you have an idea to set a relative path here? Or just why I can't do that?

Thanks

Upvotes: 1

Views: 4768

Answers (1)

Steve
Steve

Reputation: 216323

The application specific folder for the current roaming user is defined by one entry in the enum Environment.SpecialFolder and it is the ApplicationData entry

You can retrieve the path associated to this enum using Environment.GetFolderPath passing the enum entry

 string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

So in your config file you could store simply the final part Test\appfile.config and use this code

 string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
 string configLocation = Configuration.AppSettings["file"].ToString();
 string file = Path.Combine(appData, configLocation);

Upvotes: 4

Related Questions