似乎是一个微不足道的问题,但令人惊讶的是,只找到了一些像this one这样的解决方案,它们解释了如何使用弃用函数添加一些属性。我宁愿想编辑一个。那么,它是如何在.NET 4.0中完成的?
更具体地说,需要在<connectionStrings>
属性中设置数据库的位置。
答案 0 :(得分:1)
此代码改编自this blog post并在.NET 4上进行测试:
using System;
using System.Configuration;
class Program
{
static void ShowConfig()
{
// For read access you do not need to call the OpenExeConfiguraton
foreach (ConnectionStringSettings item in ConfigurationManager.ConnectionStrings)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Name, item.ConnectionString);
}
}
static void Main(string[] args)
{
ShowConfig();
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var conSettings = new ConnectionStringSettings("NewName", "New connstring value");
config.ConnectionStrings.ConnectionStrings.Add(conSettings);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
Console.WriteLine("===UPDATE===");
ShowConfig();
Console.Read();
}
}
的App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="db1" connectionString="blah"/>
</connectionStrings>
</configuration>
在我的电脑上打印
Key: LocalSqlServer, Value: data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true Key: db1, Value: blah ===UPDATE=== Key: LocalSqlServer, Value: data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true Key: db1, Value: blah Key: NewName, Value: New connstring value