insomnium_
insomnium_

Reputation: 1820

Writing appSetting to separate *.config file

I have a self-hosted web api project, which appSettings are stored in separate location. I've achieved this by using file=""

<appSettings file="D:\myLocation\api.config">
  </appSettings>

Then I'm able to read my settings using this code:

var value = ConfigurationManager.AppSettings["MyKey"];

But when I try to re-write the value, using this code:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["MyKey"].Value = "someNewValue"
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

I'm getting original app.config file updated, instead of updating my separate stored file. Is there any way of updating external appSettings file programmatically? Or maybe there are other best practices of storing settings separately?

Please, ask, if you need more information!

Thank you in advance!

Update

Just to prevent comments and answers like "wouldn't it be easier..." - this service is going to work on specific system with Enhanced Write Filter applied. This means, I won't be able to make any persistent changes on the partition. That's why I'm looking for a way to store settings in separate file located on separate partition without EWF. This scenario puts strict limits on how I can resolve the issue. Thank you for understanding!

Upvotes: 4

Views: 1336

Answers (3)

Joe Park
Joe Park

Reputation: 95

Use below.

var configFile = new FileInfo("D:\WebsiteABC\Web.config");
var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
var wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
configuration = WebConfigurationManager.OpenMappedWebConfiguration(wcfm,  "/");
configuration.AppSettings.SectionInformation.ConfigSource = "AppSettings.config";

Upvotes: 0

user3624833
user3624833

Reputation:

Why not open the external config file as a regular Xml file and write your changes? This way you dont have to worry about anything else.

Upvotes: 1

rickythefox
rickythefox

Reputation: 6861

Specify the name of the config section like this:

config.AppSettings.SectionInformation.ConfigSource = "api.config";

Upvotes: 1

Related Questions