marc3l
marc3l

Reputation: 2595

Read and write settings programmatically in C#

I've got the following example content generated by the Settings-Designer in Visual Studio 2015:

<configuration>
  <applicationSettings>
    <Test.Properties.Settings>
      <setting name="LogFileFolder" serializeAs="String">
        <value>logs</value>
      </setting>
      <setting name="sPluginsFolder" serializeAs="String">
        <value>plugins</value>
      </setting>
      <setting name="sLangBaseName" serializeAs="String">
        <value>Test.Resources.Language.Test</value>
      </setting>
      <setting name="ConfirmationExit" serializeAs="String">
        <value>True</value>
      </setting>
    </Test.Properties.Settings>
  </applicationSettings>
</configuration>

Now I want to access, for example, the variable "ConfirmationExit" within my code. In first I tried with Properties.Settings.Default which is working nicely, but I want to retrieve the configuration keys more generic and provide a ConfigurationService which can be used by any other .NET program.

I tried playing around with the ConfigurationManager, but I didn't get the values of the different settings/properties. I always got null if I tried something like this:

string test = ConfigurationManager.AppSettings["ConfirmationExit"];

How can I PROGRAMMATICALLY read AND write properties/settings defined within the app.config file with the use of the Settings-Designer. Thx for any help ;)

UPDATE:

Maybe I have to mention, that there is a namspace used as XML element (I think this is generated by the designer or soemthing else?!):

<Test.Properties.Settings>

inside of

<applicationSettings>

Also please remind: This is a project structure like this:

1. Project_Common

2. Project_Main

   |-- Project_Common

3. Project_Plugin1

   |-- Project_Common

4. Project_Plugin2

   |-- Project_Common

...

In Project_Common there should be a ConfigurationService which can retrieve all properties of all applications. Maybe the constructor has to have a parameter to inject settings or something.

Upvotes: 1

Views: 2726

Answers (2)

Tom S&#246;hne
Tom S&#246;hne

Reputation: 522

read: Settings.Default.{propertyName} so in your case for example Settings.Default.ConfirmationExit reads ConfirmationExit-Value

Set it: Settings.Default.ConfirmationExit = false

Write: Settings.Default.Save();

Upvotes: 2

Astx
Astx

Reputation: 11

            string test = Properties.Settings.Default.ConfirmationExit;

From MSDN: https://msdn.microsoft.com/en-us/library/a65txexh.aspx

Upvotes: 1

Related Questions