是否可以通过编程方式更改App.config中connectionString内的用户/密码?

时间:2018-11-02 07:38:13

标签: c# wpf model-view-controller

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="connect_cbu" connectionString="Data Source=192.168.66.67; Initial Catalog=CBU; Persist Security Info=True; User ID=Admin;Password=1234"/>   
  </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>

假设我在public static string user;内定义了以下两个字符串:public static string pass;Global.cs。是否可以通过某种方式将它们包括在connectionString中?

示例:

connectionString="Data Source=192.168.66.67; Initial Catalog=CBU; Persist Security Info=True; User ID='Global.user';Password='Global.pass'"/>

解决方案,基于TheGeneral的答案:

app.config

<connectionStrings>
<clear/>
<add name="connect_cbu" connectionString="Data Source=192.168.66.67; Initial Catalog=CBU; Persist Security Info=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

MainWindow.xaml.cs

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Windows;


namespace Test
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            OpenConnection();
            InitializeComponent();
        }

        public SqlConnection con = new SqlConnection();

        public void OpenConnection()
        {
            try
            {
                con.ConnectionString = BuildConnectionString("Admin", "1234"); 
                con.Open();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show(this, "Do you want to exit?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
            if (result != MessageBoxResult.Yes)
            {
                e.Cancel = true;
                con.Close();
            }
        }

        public static string BuildConnectionString(string userName, string userPassword)
        {
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connect_cbu"];

            if (null != settings)
            {
                string connectString = settings.ConnectionString;
                Console.WriteLine("Original: {0}", connectString);
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString)
                {
                    UserID = userName,
                    Password = userPassword
                };
                Console.WriteLine("Modified: {0}", builder.ConnectionString);
                return builder.ToString();
            }
            else
            {
                MessageBox.Show("App.config is missing!", "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
                return "fail";
            }
        }
    }
}

2 个答案:

答案 0 :(得分:6)

某些Connection String Builders可能对您有帮助

  

如果事先知道连接字符串的某些元素,则它们   可以存储在配置文件中,并在运行时检索到   构造一个完整的连接字符串。例如,   数据库可能是事先已知的,但服务器名称却未知。要么   您可能希望用户在运行时提供名称和密码   而无法将其他值插入连接字符串。

例如

<connectionStrings>  
  <clear/>  
  <add name="partialConnectString"   
    connectionString="Initial Catalog=Northwind;"  
    providerName="System.Data.SqlClient" />  
</connectionStrings>  

示例

private static void BuildConnectionString(string dataSource,
    string userName, string userPassword)
{
    // Retrieve the partial connection string named databaseConnection
    // from the application's app.config or web.config file.
    ConnectionStringSettings settings =
        ConfigurationManager.ConnectionStrings["partialConnectString"];

    if (null != settings)
    {
        // Retrieve the partial connection string.
        string connectString = settings.ConnectionString;
        Console.WriteLine("Original: {0}", connectString);

        // Create a new SqlConnectionStringBuilder based on the
        // partial connection string retrieved from the config file.
        SqlConnectionStringBuilder builder =
            new SqlConnectionStringBuilder(connectString);

        // Supply the additional values.
        builder.DataSource = dataSource;
        builder.UserID = userName;
        builder.Password = userPassword;
        Console.WriteLine("Modified: {0}", builder.ConnectionString);
    }
}
  

但是如何初始化BuildConnectionString?

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(youCurrrentConnectionString);

builder.UserID = userName;
builder.Password = userPassword;


//usage 
ConnectionString = builder.ConnectionString;

答案 1 :(得分:0)

App.Config是 Program Files 文件夹中软件的一部分,不能在安装后进行更改。

您也不应该在其中输入用户名/密码。任何人都可以阅读。

使用 ConnectionStringBuilder 并将用户名/密码存储在安全的地方。

或者如果它是MSSQL DB,则可以使用集成安全性。因此,可以在软件之外处理数据库访问安全性。