[英]asp.net dynamically add connection string in web.config
我在同一解決方案中有Web應用程序和Windows應用程序。 我想在web.config文件中動態添加連接字符串。 連接字符串信息來自Windows應用程序。 我該怎么做,請幫助我。
我的窗口應用程序具有:
WebForm1 wf = new WebForm1();
wf.add();
我的wep應用程序具有:
public void add()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConnectionStringsSection sec = (ConnectionStringsSection)config.GetSection("connectionStrings");
sec.ConnectionStrings["DBCS"].ConnectionString = "Data Source=GKS_004-PC;Database=hello1;User ID=123;Password=123";
config.Save();
}
我相信您以一種可能存在解決問題的不同方法的方式來解決您的問題,但是為了做您想做的事情,您有兩種選擇。 首先,您可以使用IO
名稱空間讀取文件,然后使用LINQ
節點像XML
一樣對其進行解析,其次您可以使用Configuration
類( System.Configuration
和System.Web.Configuration
命名空間)。
//get the configuration file
Configuration config = WebConfigurationManager.OpenWebConfiguration("..."); //path to config
//get Configuration section
ConfigurationSection section = config.GetSection("...");
config.AppSettings.Settings.Add(Key, Value);
config.AppSettings.Settings.Remove(Key);
或這樣,而不是直接使用Configuration
類
AppSettingsSection appsettings = (AppSettingsSection) config.GetSection("...");
appsettings.Settings.Add(key, Value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.