这在运行时更改连接字符串,有没有办法永久更改连接字符串? [英] This change connectionstring during runtime, Is there a way to change the connection string permanently?

查看:77
本文介绍了这在运行时更改连接字符串,有没有办法永久更改连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我发现此方法更改了连接字符串,但这仅在我运行应用程序时有效,这意味着它们是临时保存的,而不保存配置文件中的连接字符串。



按键代码:

Hello I find this method to change Connection String, but this only works while I am running the application which means they are saved temporary, without saving the connection string in configuration file.

Button code:

private void Regbtn_Click(object sender, RoutedEventArgs e)
{
        try
        {
            //Constructing connection string from the inputs
            StringBuilder Con = new StringBuilder("Data Source=");
            Con.Append(servertext.Text);
            Con.Append(";Initial Catalog=");
            Con.Append(DBname.Text);
            Con.Append(";Integrated Security=SSPI;");
            string strCon = Con.ToString();
            updateConfigFile(strCon);
            //Create new sql connection
            SqlConnection Db = new SqlConnection();
            //to refresh connection string each time else it will use             previous connection string
            ConfigurationManager.RefreshSection("connectionStrings");
            Db.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            //To check new connection string is working or not
            MessageBox.Show(Connection.GetConnectionString());
        }
        catch (Exception E)
        {
            MessageBox.Show(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString() + ".This is invalid connection", "Incorrect server/Database");
        }
    }










public void updateConfigFile(string con)
{
    //updating config file
    XmlDocument XmlDoc = new XmlDocument();
    //Loading the Config file
    XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    foreach (XmlElement xElement in XmlDoc.DocumentElement)
    {
        if (xElement.Name == "connectionStrings")
        {
            //setting the coonection string
            xElement.FirstChild.Attributes[2].Value = con;
        }
    }
    //writing the connection string in config file
    XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}

推荐答案

将连接字符串存储在app.config- 如何从C#中的App.Config获取连接字符串 [ ^ ]。

另一个例子 - 使用C#和VB.Net从App.Config文件读取(获取)连接字符串 [ ^ ]



更新app.config中的连接字符串 - 将连接字符串保存到app.config [ ^ ]。
Store the connection string in app.config-How to get Connection String from App.Config in C#[^].
Another example - Read (Get) Connection String from App.Config file using C# and VB.Net[^]

Update connection strings in app.config - Saving Connection Strings to app.config[^].


这篇关于这在运行时更改连接字符串,有没有办法永久更改连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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