是否可以在运行时修改配置 ConnectionStrings? [英] Is it possible to modify configuration ConnectionStrings at runtime?

查看:27
本文介绍了是否可以在运行时修改配置 ConnectionStrings?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时修改 app.config/web.config 中定义的连接字符串?我想根据运行应用程序/站点的机器使用不同的配置文件(当然,仅用于调试目的.我们将在部署时使用常规配置文件).

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 (AFAIK).或者我可以吗?

I can write AppSettings, but not ConnectionStrings (AFAIK). Or can I?

推荐答案

是的,这是可能的,但 AFAIK 只能通过 Reflection.以下代码应该可以满足您的需求(阅读下文了解用法):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆