简体   繁体   中英

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM