【问题标题】:Accessing App.config访问 App.config
【发布时间】:2024-01-21 15:12:01
【问题描述】:

我的 App.config 中有以下内容,如何使下面的代码工作????

configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="WpfDatabind3.Properties.Settings.cbfSQL1ConnectionString"
            connectionString="Data Source=STEPHANS-PC\SQLEXPRESS;Initial Catalog=cbfSQL1;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

我不知道如何访问 App.config 中的连接字符串。

DataSet myDataSet;

private void OnInit(object sender, EventArgs e)
{
  string mdbFile = Path.Combine(AppDataPath, "BookData.mdb");
  string connString = string.Format(
      "Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", mdbFile);
  OleDbConnection conn = new OleDbConnection(connString);
  OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM BookTable;", conn);

  myDataSet = new DataSet();
  adapter.Fill(myDataSet, "BookTable");

  // myListBox is a ListBox control. 
  // Set the DataContext of the ListBox to myDataSet
  myListBox.DataContext = myDataSet;
}

【问题讨论】:

    标签: c# configuration connection-string app-config


    【解决方案1】:

    System.Configuration.dll 的引用添加到您的项目中。然后使用ConfigurationManager 类。它允许按名称获取连接字符串设置:

    string connString = ConfigurationManager
       .ConnectionStrings["WpfDatabind3.Properties.Settings.cbfSQL1ConnectionString"]
       .ConnectionString;
    

    【讨论】:

    • 不,当前上下文中不存在名称“ConfigurationManager”。
    • 那你错过了参考
    • 是的,我是,我知道我把它放进去,但是当我重新检查它时它不在那里。现在我必须在上下文中获取 myDataSet'