如何在asp.net web.config中动态设置连接字符串 [英] How to set a connection string dynamically in asp.net web.config
问题描述
嗨
i有一个要求管理员设置连接字符串的要求。所以我想把一个mycon.txt文件放在c:/连接位置并读取我的应用程序中的文本(连接字符串)。
问题是我可以阅读文本,但我不知道如何将文本设置为web中的连接字符串。 config。
i使用下面的代码来读取文件
string text = System.IO.File.ReadAllText(@C:\\ \\\connection\\mycon.txt);
任何人都可以帮助我,是否可以设置在web.config中动态连接字符串。谢谢提前
hi
i have a requirment that the admin will set the connection string .so i thought to place a mycon.txt file in c:/connection location and read the text(connection string) in my application.
The problem is i can read the text but i dont know how to set the text as my connection string in web.config .
i used the below code to read the file
string text = System.IO.File.ReadAllText(@"C:\\connection\\mycon.txt");
can any one help me out,is it posible to set the connection string dynamically in web.config .Thanks in Advance
推荐答案
这是要解决的代码:
Here is the code to resolve:
public void SetDynamicConnectionString(string server, string database, string userid, string password)
{
string str = "server=" + server + ";database=" + database + "; User ID=" + userid + "; Password=" + password + "";
System.Configuration.Configuration dynConfig = WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection connStringSection = (ConnectionStringsSection)dynConfig.GetSection("connectionStrings");
ConnectionStringSettings StringSettings = new ConnectionStringSettings("conn", "Data Source=" + server + ";Database=" + database + ";User ID=" + userid + ";Password=" + password + ";");
connStringSection.ConnectionStrings.Remove(StringSettings);
connStringSection.ConnectionStrings.Add(StringSettings);
dynConfig.Save(ConfigurationSaveMode.Modified);
}
这篇关于如何在asp.net web.config中动态设置连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!