c# - 在 C# winforms 中覆盖存储在 app.config 中的连接字符串

标签 c# winforms runtime app-config

您好,我正在开发一个应用程序,我在第一次运行时动态地从用户获取连接字符串。

我的app.config是

 <connectionStrings>
 <add name="DConnection" connectionString=""
     providerName="MySql.Data.MySqlClient"/>
 <add name="SConnection" connectionString="" 
     providerName="System.Data.SqlClient" />
 </connectionStrings>

我正在使用以下方法将连接字符串分配给 app.config 的属性

private void CheckingSource(string constr)
    {
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.ConnectionStrings.ConnectionStrings["SConnection"].ConnectionString = constr; //CONCATINATE YOUR FIELDS TOGETHER HERE
        config.Save(ConfigurationSaveMode.Modified, true);
        ConfigurationManager.RefreshSection("connectionStrings");
    }

private void CheckingDestination(string constr)
    {
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.ConnectionStrings.ConnectionStrings["DConnection"].ConnectionString = constr; //CONCATINATE YOUR FIELDS TOGETHER HERE
        config.Save(ConfigurationSaveMode.Modified, true);
        ConfigurationManager.RefreshSection("connectionStrings");
    }

现在我必须将此连接字符串写入 app.config,以便用户下次运行应用程序时应该使用这些更新的连接字符串。

我们如何管理它?我不知道,因为我对 app.config 及其用法还比较陌生。

最佳答案

Now I have to write this connection string to app.config so when user run application next time these updated connection strings should be in use.

你不应该这样做,app.config 文件可能会部署到像 C:\Program Files\Your Application 这样的地方,不是 普通用户可写。

相反,以不同于使用 ConfigurationManager.ConnectionStrings 的方式为任何需要它的人提供连接字符串。

using (var connection = new SqlConnection(GetConnectionStringFromUser())) { ...

关于“保存”连接字符串的具体问题,您应该查看某种持久性机制,例如 .NET 的 Application Settings。 .

The application settings architecture supports defining strongly typed settings with either application or user scope, and persisting the settings between application sessions.

关于c# - 在 C# winforms 中覆盖存储在 app.config 中的连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20299158/

相关文章:

c# - Rigidbody2D 在撞到对撞机时停止

c# - C# 中的变量泛型返回类型

c# - 检测前台窗口的哪个子窗口被点击?

c# - 更改表单上的所有按钮

java - 是否可以在运行时更改 UI 并将更改保存在 android 应用程序中?

java - 通过热交换机制在运行时更改方法

c# - 隔离存储问题

c# - 如何位于全屏应用程序顶部但不位于顶部

c# - 围绕曲线绘制包络

java - Wicket - 运行时类重新加载