Write values in app.config file

后端 未结 10 922
生来不讨喜
生来不讨喜 2020-11-29 01:46

can anyone please help me how can I set/store values in the app.config file using c#, is it possible at all?

相关标签:
10条回答
  • 2020-11-29 01:48

    Try the following code:

        Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
        config.AppSettings.Settings.Add("YourKey", "YourValue");
        config.Save(ConfigurationSaveMode.Minimal);
    

    It worked for me :-)

    0 讨论(0)
  • 2020-11-29 01:51

    Try the following:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);            
    config.AppSettings.Settings[key].Value = value;
    config.Save();
    ConfigurationManager.RefreshSection("appSettings");
    
    0 讨论(0)
  • 2020-11-29 01:56

    If you are using App.Config to store values in <add Key="" Value="" /> or CustomSections section use ConfigurationManager class, else use XMLDocument class.

    For example:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
        <add key="server" value="192.168.0.1\xxx"/>
        <add key="database" value="DataXXX"/>
        <add key="username" value="userX"/>
        <add key="password" value="passX"/>
      </appSettings>
    </configuration>
    

    You could use the code posted on CodeProject

    0 讨论(0)
  • 2020-11-29 01:57

    Yes you can - see ConfigurationManager

    The ConfigurationManager class includes members that enable you to perform the following tasks:

    • Read and write configuration files as a whole.

    Learn to use the docs, they should be your first port-of call for a question like this.

    0 讨论(0)
  • 2020-11-29 02:02
    //if you want change
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings[key].Value = value;
    
    //if you want add
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Add("key", value);
    
    0 讨论(0)
  • 2020-11-29 02:05

    On Framework 4.5 the AppSettings.Settings["key"] part of ConfigurationManager is read only so I had to first Remove the key then Add it again using the following:

    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    
    config.AppSettings.Settings.Remove("MySetting");
    config.AppSettings.Settings.Add("MySetting", "some value");
    
    config.Save(ConfigurationSaveMode.Modified);
    

    Don't worry, you won't get an exception if you try to Remove a key that doesn't exist.

    This post gives some good advice

    0 讨论(0)
提交回复
热议问题