[英]how to manipulate connectionstring in app.config file?
我試圖在運行時設置connectionstring
字符串。 我需要的是在運行時設置datasource
並重啟應用程序。 我在谷歌找到了一些方法,但問題是app.config
在Application.Restart();
之后恢復到默認值Application.Restart();
我試圖在settings.cs
和app.config
保存connectionstring
,但它對我不起作用。 這是我的代碼:
public void setConnectionString()
{
try
{
string str = string.Empty;
str = string.Format(@"Data Source={0}; Initial Catalog=CRM01_DB; UID= {1}; PWD={2}", Default.DataSource, Default.UID, Default.UPass);
this["CRM01_DBConnectionString"] = str;
Default.Save();
Thread.Sleep(100);
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["CRM01_DBConnectionString"].ConnectionString = str;
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
Thread.Sleep(100);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
我沒有得到任何錯誤,但是當應用程序啟動時, connectionstrig
具有默認值
如果您從VS測試此代碼,它可能不起作用(可能不會)。
從VS運行時,實際執行的程序是<your_program>.vshost.exe
,相應的.config
文件名為<your_program>.vshost.exe.config
,您應該檢查那里的更改。
但..
VS保持原始.config
和.vshost.exe.config
同步,以便您看不到您的更改。
要測試代碼是否有效,請從VS外部嘗試或取消選中Enabled the Visual Studio hosting process
( Properties
- > Debug
)(請記住它有影響 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.