简体   繁体   English

更新资料 <appSettings> 在App.config winForm C#中

[英]Update <appSettings> in App.config winForm C#

I write class when the program run, it check Connection to SQL Server. 我在程序运行时编写类,它检查到SQL Server的连接。 if the connection is not Ok, the new form Show up and ask for ServerName, DBName, UserName, and Password , then check the connection again if it is Ok it enter the program 如果连接不正确,则显示新表单并询问ServerName,DBName,UserName和Password,然后再次检查连接是否正确,然后输入程序

I write Code if new information For connection Ok It save in App.Config But It doesn't Work 如果有新信息,我会编写代码以进行连接确定将其保存在App.Config中,但不起作用

public static void SaveToConfig(string key,string value)
    {
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.AppSettings.Settings[key].Value = value;
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");

    }

Try this, 尝试这个,

First, include using a statement like : 首先,使用如下语句:

1 using System.Configuration; 1.使用System.Configuration;

2 Edit App.config so that you add your settings in the appSetting.config file and add an element with key and value parameters eg 2编辑App.config,以便将设置添加到appSetting.config文件中,并添加具有键和值参数的元素,例如

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

    <appSettings>
      <add key="server" value="localhost" />
      <add key="port" value="5432" />
      <add key="username" value="myusername" />
      <add key="password" value="mypass" />
      <add key="database" value="mydb" />
    </appSettings>
</configuration>

Now you can access your settings in your given code. 现在,您可以在给定的代码中访问您的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM