是否可以在运行时修改 app.config/web.config 中定义的连接字符串?我想根据运行应用程序/站点的机器使用不同的配置文件(当然,仅用于调试目的。我们将在部署时使用常规配置文件)。
我可以编写 AppSettings,但不能编写 ConnectionStrings (AFAIK)。或者我可以吗?
是否可以在运行时修改 app.config/web.config 中定义的连接字符串?我想根据运行应用程序/站点的机器使用不同的配置文件(当然,仅用于调试目的。我们将在部署时使用常规配置文件)。
我可以编写 AppSettings,但不能编写 ConnectionStrings (AFAIK)。或者我可以吗?
是的,这是可能的,但 AFAIK 只能通过反射。以下代码应该可以满足您的需求(请阅读下文了解用法):
public static string SetConnectionString(Type assemblyMember,
Type settingsClass,
string newConnectionString,
string connectionStringKey)
{
Type typSettings = Type.GetType(Assembly.CreateQualifiedName(assemblyMember.Assembly.FullName, settingsClass.FullName));
if (typSettings == null)
{
return null;
}
PropertyInfo prpDefault = typSettings.GetProperty("Default", BindingFlags.Static | BindingFlags.Public);
if (prpDefault == null)
{
return null;
}
object objSettings = prpDefault.GetValue(null, null);
if (objSettings == null)
{
return null;
}
// the default property, this[], is actually named Item
PropertyInfo prpItem = objSettings.GetType().GetProperty("Item", BindingFlags.Instance | BindingFlags.Public);
if (prpItem == null)
{
return null;
}
object[] indexerName = { connectionStringKey };
string oldConnectionString = (string)prpItem.GetValue(objSettings, indexerName);
prpItem.SetValue(objSettings, newConnectionString, indexerName);
return oldConnectionString;
}
assemblyMember
是调用类型
settingsClass
是您的设置类型是要设置
newConnectionString
的完整字符串
connectionStringKey
是您在应用程序设置中定义的连接字符串的名称
您应该在应用程序启动后尽快调用此方法,最好是在 Main() 方法中。
您无法真正编辑正在运行的进程的配置文件。
一种选择(有利有弊)是在 machine.config 或主 web.config 中使用配置数据(对于“站点”,您使用“位置”节点)——不过,这不是一个匆忙的选项。
处理此问题的更好方法是将配置文件作为构建/部署过程的一部分进行交换,理想情况下是自动化的。这样,一切都是独立的,您可以“robocopy”到普通服务器并让它工作。
重新考虑您的“每个开发人员”点;我发现最简单的方法是标准化配置并调整机器。例如,我们在 VM 上运行本地 Web 服务器;我们不是针对每台机器编写代码,而是对“localserver”进行标准化(镜像“localhost”),并向开发人员可以控制的每台机器添加本地 DNS 记录。请注意,这需要固定的 IP 地址(或者可能是 DHCP 预留)以防止它随着时间的推移而改变!
同上数据库;本地服务器可以使用“.”;远程服务器可以在机器上使用别名,因此“devserver”指向用户想要的任何内容。
只是一个想法...
我在我的项目中尝试过一次以进行调试但无法做到,问题(我想,如果我错了,请纠正我)是在应用程序启动时 app.config 被加载到内存中,对 app.config 的任何更改在应用程序运行时不会得到反映。
为了克服这个问题,我在 app.config 中定义了所有连接字符串,然后在程序像这样运行时调用所需的连接字符串。
例如,假设您在 app.config 中定义了您的连接字符串,如下所示。
<connectionStrings>
<add name="YourNameSpace.Properties.Settings.ConnectionString_1"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=|DataDirectory|\file.mdb"
providerName="System.Data.OleDb"/>
<add name="YourNameSpace.Properties.Settings.ConnectionString_2"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=|DataDirectory|\file.mdb"
providerName="System.Data.OleDb"/>
</connectionStrings>
定义任意数量(您正在调试正确:-))然后在代码中调用这些连接设置执行以下操作:
YourNameSpace.Properties.Settings foo = new YourNameSapce.Properties.Settings();
foo.ConnectionString_1;
高温高压
最好的祝福
@nand
PS:这个回复是针对C#的。
安装网站时,您可以在 NAnt 脚本中运行 xmlpoke。
例如