akd
akd

Reputation: 6740

How to use App.config File?

I have created a simple windows application and added a App.config file

I have also added Settings file which also adds keys into App.config file.

<appSettings> 
    <add key="myKey" value="1"/>    
</appSettings>
<applicationSettings>
    <MyApp.AppSettings>
        <setting name="RunAutomated" serializeAs="String">
            <value>False</value>
        </setting>
    </MyApp.AppSettings>
</applicationSettings>

Inside my code have the following :

If(AppSettings.Default.RunAutomated) {
    Console.WriteLine("Running auto!!!");
}
else { 
    Console.WriteLine("Running manual!!!");
}

Simple is that.

When I build the project and run it through visual studio everything is as expected that output changes when I change RunAutomated key and re run the application.

But this is not true when I go under /bin/Debug folder and run the MyApp.exe

It seems to cache app.config and it ignores the changes to app.config file.

How should I do this simple task to keep reading the App.config file every time it is run? any changes I am making app.config should affect the application?

Upvotes: 0

Views: 383

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157098

If you have altered the property in code, or using a UI in your app, you should save the altered properties by calling Save on the SettingsBase instance:

AppSettings.Default.Save();

Note that after every build the settings file is overwritten, so try to copy the executable to another folder and run it multiple times.

Alternatively you can create your own settings file, which I find easier and more reliable. You can take a look at the XmlSerializer class and the JsonConvert class in Newtonsoft Json.

Upvotes: 1

Related Questions