2011-05-09 120 views
0

我的樣本app.config文件是如何在app.config文件中設置連接字符串值?

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <connectionStrings> 
    <add name="DBconn" connectionString="driver={MySQL ODBC 5.1 Driver};server=10.78.17.229;database=grocery;uid=root;pwd=admin;"/> 
    </connectionStrings> 
</configuration> 

我想設置從C#代碼的ConnectionString值。 我無法更改文件內容。請幫幫我。

+1

你通常只具有寫權限,當您運行整個應用程序作爲管理員,不是一個好理念。 – 2011-05-09 07:01:39

回答

0

不完全確定這是你應該採取的方法,但無論如何,這可能適合你?

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
ConfigurationSectionCollection sections = config.Sections; 

foreach (ConfigurationSection section in sections) 
{ 
    ConnectionStringsSection connSettings = section as ConnectionStringsSection; 

    if (connSettings != null) 
    { 
     connSettings.ConnectionStrings[0].ConnectionString = "...."; 
    } 
} 
+0

謝謝, Chaitanya – user626660 2011-05-11 04:20:04

1

App.cofig代碼

 <?xml version="1.0" encoding="utf-8"?> 
     <configuration> 
    <configSections> 
      <section name="dataConfiguration"type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral,  PublicKeyToken=b03f5f7f11d50a3a" /> 
    </configSections> 
    <connectionStrings> 
    <add name="DbDatabase" providerName="System.Data.SqlClient" connectionString=""/> 
</connectionStrings> 

C#代碼

public void updateConfigFile(string con) 
    { 
     //updating config file 
     XmlDocument XmlDoc = new XmlDocument(); 
     //Loading the Config file 
     XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); 
     // XmlDoc.Load("App.config"); 
     foreach (XmlElement xElement in XmlDoc.DocumentElement) 
     { 
      if (xElement.Name == "connectionStrings") 
      { 
       //setting the coonection string 
       xElement.FirstChild.Attributes[2].Value = con; 
      } 
     } 
     //writing the connection string in config file 
     XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); 
     //XmlDoc.Save("App.config"); 
    } 



private void btn_Connect_Click(object sender, EventArgs e) 
    { 
     StringBuilder Con = new StringBuilder("Data Source="); 
     Con.Append(txt_ServerName.Text); 
     Con.Append(";Initial Catalog="); 
     Con.Append(txt_DatabaseName.Text); 
     if (String.IsNullOrEmpty(txt_UserId.Text) &&String.IsNullOrEmpty(txt_Password.Text)) 
      Con.Append(";Integrated Security=true;"); 
     else 
     { 
      Con.Append(";User Id="); 
      Con.Append(txt_UserId.Text); 
      Con.Append(";Password="); 
      Con.Append(txt_Password.Text); 
     } 
     string strCon = Con.ToString(); 
     updateConfigFile(strCon); 

     DatabaseTableDA da = new DatabaseTableDA(); 
     tableList = da.Select_Tables(); 
     this.lstTables.DataSource = tableList; 
    } 
+0

請在答案中詳細說明您的答案與以前的答案有何不同。 (鑑於OP對上一個答案的評論似乎解決了這個問題) – 2013-07-18 15:01:07

相關問題