c# - 删除硬编码值到 app.config 文件

标签 c# visual-studio winforms

我开发了一个表单,它从用户那里获取用户 ID 和密码,并显示本地服务器中可用的数据库列表。现在我已经用硬编码格式完成了...就像这样

public void BindDBDropDown()
{
    //Create the connection object
    SqlConnection sConnection = new SqlConnection(
        ConfigurationSettings.AppSettings["ConnectionString"]);

    //To Open the connection.
    sConnection.Open();

    //Query to select the list of databases.
    string selectDatabaseNames =
        @"SELECT NAME FROM MASTER..SYSDATABASES";

    //Create the command object
    SqlCommand sCommand = 
        new SqlCommand(selectDatabaseNames, sConnection);

    try
    {
        //Create the data set 
        DataSet sDataset = new DataSet("master..sysdatabases");

        //Create the dataadapter object
        SqlDataAdapter sDataAdapter = 
            new SqlDataAdapter(selectDatabaseNames, sConnection);
        sDataAdapter.TableMappings.Add("Table", 
            "master..sysdatabases");

        //Fill the dataset
        sDataAdapter.Fill(sDataset);

        //Bind the database names in combobox
        DataViewManager dsv = sDataset.DefaultViewManager;

        //Provides the master mapping between the sourcr table 
        //and system.data.datatable
        cmbDatabases.DataSource = 
            sDataset.Tables["master..sysdatabases"];
        cmbDatabases.DisplayMember = "NAME";
        cmbDatabases.ValueMember = ("NAME");
    }
    catch(Exception ex)
    {
        //All the exceptions are handled and written in the EventLog.
        EventLog logException = new EventLog("Application");
        logException.Source = "MFDBAnalyser";
        logException.WriteEntry(ex.Message);
    }
    finally
    {
        //If connection is not closed then close the connection
        if(sConnection.State != ConnectionState.Closed)
        {
            sConnection.Close();
        }
    }
}

/// <summary>
///This function binds the names of all the tables with primary 
///keys in a dropdown cmbResults.
/// </summary>
public void GetPrimaryKeyTable()
{
    //An instance of the connection string is created to manage
    //the contents of the connection string.
    var sqlConnection = new SqlConnectionStringBuilder();
    sqlConnection.DataSource = "192.168.10.3";
    sqlConnection.UserID = "gp";
    sqlConnection.Password = "gp";
    sqlConnection.InitialCatalog = 
        Convert.ToString(cmbDatabases.SelectedValue);
    string connectionString = sqlConnection.ConnectionString;

    SqlConnection sConnection = new SqlConnection(connectionString);

    //To Open the connection.
    sConnection.Open();

    //Query to select the table_names that have PRIMARY_KEYS.
    string selectPrimaryKeys = @"
        SELECT  TABLE_NAME 
        FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        WHERE   CONSTRAINT_TYPE = 'PRIMARY KEY'
        AND     TABLE_NAME <> 'dtProperties'
        ORDER BY TABLE_NAME";

    //Create the command object
    SqlCommand sCommand = 
        new SqlCommand(selectPrimaryKeys, sConnection);

    try
    {
        //Create the dataset
        DataSet dsListOfPrimaryKeys = 
            new DataSet("INFORMATION_SCHEMA.TABLE_CONSTRAINTS");

        //Create the dataadapter object
        SqlDataAdapter sDataAdapter = 
            new SqlDataAdapter(selectPrimaryKeys, sConnection);

        //Provides the master mapping between the sourcr table 
        //and system.data.datatable
        sDataAdapter.TableMappings.Add("Table", 
            "INFORMATION_SCHEMA.TABLE_CONSTRAINTS");

        //Fill the dataset
        sDataAdapter.Fill(dsListOfPrimaryKeys);

        //Bind the result combobox with primary key tables
        DataViewManager dvmListOfPrimaryKeys = 
            dsListOfPrimaryKeys.DefaultViewManager;
        dgResultView.DataSource = dsListOfPrimaryKeys
            .Tables["INFORMATION_SCHEMA.TABLE_CONSTRAINTS"];
    }
    catch(Exception ex)
    {
        //All the exceptions are handled and written in the EventLog.
        EventLog log = new EventLog("Application");
        log.Source = "MFDBAnalyser";
        log.WriteEntry(ex.Message);
    }
    finally
    {
        //If connection is not closed then close the connection
        if(sConnection.State != ConnectionState.Closed)
        {
            sConnection.Dispose();
        }
    }
}

谁能帮我删除这些硬编码的东西并直接从 app.config 文件中获取本地服务器地址、用户 ID 和密码???

最佳答案

当然可以。

首先,打开您的 app.config 或 web.config 文件。

查找以下部分

<appSettings>
    <add key="...." value="....." />
    ....
</appSettings>

如果不存在,则应添加。

现在添加以下键/值...

<add key="myServer" value="192.168.10.3" />
<add key="myUserId" value="gp" />
<add key="myPassword" value="gp" />

这是 app.config 现在的样子...

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>  
      <add key="myServer" value="192.168.10.3" />
      <add key="myUserId" value="gp" />
      <add key="myPassword" value="gp" />
   </appSettings>
</configuration> 

基尔。现在让我们更新代码。诀窍是使用 ConfigurationManager.AppSettings类:-

改变...

sqlConnection.DataSource = "192.168.10.3";
sqlConnection.UserID = "gp";
sqlConnection.Password = "gp";

为了..

sqlConnection.DataSource = ConfiguationManager.AppSettings["myServer"];
sqlConnection.UserID = ConfiguationManager.AppSettings["myUserId"];
sqlConnection.Password = ConfiguationManager.AppSettings["myPassword"];

现在您可以更改这些键/值的值(在 app.config 或 web.config 中)而无需编译代码:)

HTH

关于c# - 删除硬编码值到 app.config 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4333545/

相关文章:

c# - 减少 if 语句本身

c# - 在一个可靠的解决方案中集成用 Python 编写的测试和用 C# 编写的测试

c# - 我应该使用 using 语句来创建 Windows.Forms.Form 对象吗?

c# - GZip header 中的魔数(Magic Number)不正确。确保您传递的是 GZip 流

c# - 如何将 ItemsSource 绑定(bind)到私有(private)属性

c# - 使用带有智能卡证书的signedCms 时出错

c# - Visual Studio 项目 : How to include a reference for one configuration only?

visual-studio - Office 加载项重新安装错误 : Could not Load File or Assembly

c# - 部署程序

c# - 是否可以从 Excel 电子表格 (VBA) 中获取 WinForms "Button"?