John Batdorf
John Batdorf

Reputation: 2542

C# writing to app.config file

I understand how to get a handle and write to this:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
  <appSettings>  
    <add key="Param1" value="" />  
    <add key="Param2" value="" />  
    <add key="Param3" value="" />  
  </appSettings>  
</configuration> 

But what about when it's structured like this?

<configuration>
    <userSettings>
        <MyEXEName.Properties.Settings>
            <setting name="some_setting" serializeAs="String>
                <value>some value</value>
            </setting>
        </MyEXEName.Properties.Settings>
    </userSettings>
</configuration>

Upvotes: 1

Views: 6343

Answers (3)

Marco Medrano
Marco Medrano

Reputation: 73

string someSetting = Settings.Default.some_setting;

This file is auto generated by the VS you can open it in project->properties->Settings.settings. When you execute the application note that this setting is saved in %APPDATA% that is the application user folder (you can search *.config because the folder inside %APPDATA% has a random name).

Upvotes: 0

Xint0
Xint0

Reputation: 5389

.Net Framework and Visual Studio are kind enough to generate a static Properties class on your application namespace. You can access and set the user settings through this class. Take into account that the settings values are saved in the user's roaming profile, so even though the config file in your app's folder has some settings, the user settings are saved somewhere in %USERPROFILE%\AppData.

Following the provided info, you would access the property like:

MyEXEName.Properties.Settings.some_setting = "new value";

Upvotes: 0

Adam Lear
Adam Lear

Reputation: 38768

Then you want Application Settings.

Here's an example (lifted from MSDN):

public class MyUserSettings : ApplicationSettingsBase
{
    [UserScopedSetting()]
    [DefaultSettingValue("white")]
    public Color BackgroundColor
    {
        get
        {
            return ((Color)this["BackgroundColor"]);
        }
        set
        {
            this["BackgroundColor"] = (Color)value;
        }
    }
}

Then you can use it like this:

MyUserSettings mus;

private void Form1_Load(object sender, EventArgs e)
{
    mus = new MyUserSettings();
    mus.BackgroundColor = Color.AliceBlue;
    this.DataBindings.Add(new Binding("BackColor", mus, "BackgroundColor"));
}

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    mus.Save();
}

I recommend reading the whole section on MSDN, though, as it provides lots of useful information.

Upvotes: 1

Related Questions