我正在使用数据集,ConnectionString 存储在项目属性中。我试图编辑 ConnectionString 的值,但我收到消息说它是只读的!
我需要修改 ConnectionString,因为当我的应用程序部署到客户端时我必须更改它(需要更改用户和密码)。
那么如何修改 ConnectionString 呢?
我正在使用数据集,ConnectionString 存储在项目属性中。我试图编辑 ConnectionString 的值,但我收到消息说它是只读的!
我需要修改 ConnectionString,因为当我的应用程序部署到客户端时我必须更改它(需要更改用户和密码)。
那么如何修改 ConnectionString 呢?
Put it in your app.config (of course this could be improved or you could put the entire ConnectionString into the app.config like Karl Anderson mentioned) and don´t forget to Reference System.Configuration
<appSettings>
<add key="dbServer" value="server"/>
<add key="dbName" value="mydb"/>
<add key="integratedSecurity" value="true"/>
<add key="user" value=""/>
<add key="pwd" value=""/>
</appSettings>
and in C#
public string GetConnectionString()
{
var builder = new SqlConnectionStringBuilder();
builder.DataSource = ConfigurationManager.AppSettings["dbServer"];
builder.InitialCatalog = ConfigurationManager.AppSettings["dbName"];
builder.IntegratedSecurtiy = Convert.ToBoolean(ConfigurationManager.AppSettings["integratedSecurity"]);
string user = ConfigurationManager.AppSettings["user"];
string pwd = ConfigurationManager.AppSettings["pwd"]
if(!string.IsNullOrEmpty(user))
{
builder.UserId = user;
builder.Password = YourCryptoProvider.Decrypt(pwd);
}
return builder.ToString()
}
Use the connectionStrings
section of web.config, like this:
<connectionStrings>
<add name="MyConnectionString"
connectionString="Data Source=YourComputer\sqlexpress;Initial
Catalog=YourDatabase;User ID=YourUserName;Password=YourPassword"
providerName="System.Data.SqlClient" />
</connectionStrings>
Then you can read the value in your code, like this:
Configuration rootWebConfig = Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
ConnectionStringSettings connString;
// Are there any connection string values in web.config?
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
// Find the particular connection string we want by name
connString = rootWebConfig.ConnectionStrings.ConnectionStrings["MyConnectionString"];
// Does the connection string exist in web.config?
if (connString != null)
{
// Yes, so use it here
else
{
// No, so generate error or alert user or whatever here
}