如何在运行时更改DbEntry设置

时间:2011-07-28 15:21:55

标签: c# asp.net mysql

我想更改我在Web.config文件中存储的数据库字符串连接,具体取决于运行应用程序的位置。

我知道如何阅读但是,有人知道如何改变它吗?

3 个答案:

答案 0 :(得分:0)

http://geekswithblogs.net/AzamSharp/archive/2005/10/09/56457.aspx

第三个链接出现BING search

    private void GetConfigSettings() 
    {
        string path = Server.MapPath("Web.config"); 
        string newConnectionString = @"(Your connection string here)"; 

        XmlDocument xDoc = new XmlDocument(); 
        xDoc.Load(path); 

        XmlNodeList nodeList = xDoc.GetElementsByTagName("appSettings"); 

        XmlNodeList nodeAppSettings = nodeList[0].ChildNodes; 

        XmlAttributeCollection xmlAttCollection = nodeAppSettings[0].Attributes;
        xmlAttCollection[0].InnerXml = txtKey.Text; // for key attribute
        xmlAttCollection[1].InnerXml = newConnectionString; // for value attribute

        xDoc.Save(path); // saves the web.config file         

    }

答案 1 :(得分:0)

基于您对我原来回答的评论的新答案

您可以使用String.Replace函数。 ConnectionString只是一个字符串。

string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
connectionString = connectionString.Replace("TextToReplace", "ReplacementText");

所以假设你的连接字符串是

"Data Source=LiveDbServer;Initial Catalog=MyDataBase;Persist Security Info=True;User ID=someUserId;Password=yourPassword"

您可以使用以下逻辑

if(System.Environment.ServerName == "MyTestServer")
{
   connectionString = connectionString.Replace("LiveDbServer", "TestDbServer");
}

以下是基于猜测为什么您可能希望在运行时根据运行应用程序的服务器更改连接字符串

尽管如此(如果您的目标是始终让测试Web服务器指向您的测试数据库服务器并且您的实时Web服务器指向您的实时数据库服务器,那么 更简单的方法是edit the HOSTS file。 (我确定还有其他选择,但这对我们来说是一个简单的hack,它适用于数据库连接,Web服务引用等。)

只需在测试机器上设置hosts文件,使其将“MyLiveDbServer”映射到“MyTestDbServer”的ipaddress,并且中提琴 - 您的应用程序将自动指向测试服务器而无需任何额外的代码或配置,并且所有的时间。

答案 2 :(得分:0)

我曾经在global.asax的Application_Start事件中将连接字符串加载到Application对象中(无论好坏)。

然后,我可以选择检查我正在运行的服务器并将该连接字符串加载到Application对象中,而不仅仅依赖于web.config中的单个条目。

示例:

<connectionStrings>
  <add name="testservername" connectionString="..." providerName="..."/>
  <add name="prodservername" connectionString="..." providerName="..."/>
  <add name="localhost"      connectionString="..." providerName="..."/>
</connectionStrings>

...在global.asax:

<%@ Import Namespace="System.Configuration.ConfigurationManager" %>
...
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
  Application("cn") = ConnectionStrings(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_HOST"))
End Sub

那么,每次 使用ConnectionStrings("cn")时,我都会使用Application("cn")

检查每个服务器上HTTP_HOST提供的内容,并相应地命名连接字符串。

或者,您可以全部使用ConnectionStrings(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_HOST")),而不是将整个字符串存储在Application中。

另一种选择是将主机名存储在Application变量中,以便在需要时传递给ConnectionStrings