是否有可能在运行时修改配置的ConnectionStrings? [英] Is it possible to modify configuration ConnectionStrings at runtime?
问题描述
是否有可能修改在运行时的app.config / web.config中定义的ConnectionStrings?我想用这取决于应用程序/站点上运行计算机上的不同configfiles(仅用于调试的目的,当然,我们会使用常规的配置文件中部署时)。
Is it possible to modify the connectionstrings defined in the app.config/web.config at runtime? I want to use different configfiles depending on the machine the app/site is run on (only for debugging purposes, of course. We'll use the regular config files when deployed).
我可以写的AppSettings,但不是的ConnectionStrings(据我所知)。或者,可以吗?
I can write AppSettings, but not ConnectionStrings (AFAIK). Or can I?
推荐答案
是的,它是可能的,但据我所知只有通过反思。下面的代码应该做你需要什么(阅读下面的使用):
Yes it's possible, but AFAIK only via Reflection. The following code should do what you need (read below for usage):
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
是您在您的应用程序的设置
assemblyMember
is the calling type
settingsClass
is the type of your settings class
newConnectionString
is the full string to set
connectionStringKey
is the name of the connection string that you defined in your app's settings
您应该尽快您的应用程序启动后调用此方法,最好是在main()方法。
You should call this method as soon as possible after your app has started, preferably in the Main() method.
这篇关于是否有可能在运行时修改配置的ConnectionStrings?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!