以编程方式更改C#中的连接字符串

时间:2015-06-06 02:58:36

标签: c# connection-string

我需要在我的系统中进行连接设置(在运行时更改连接字符串)。我的意思是用户可以设置并连接到他们想要的任何服务器。我的问题是,如何检索用户在连接设置中创建的最后一个连接字符串,并在用户重新运行程序时使用它?

到目前为止,这是我所做的:

connect = "Data Source=" + Class1.DS.ToString() + ";Initial Catalog=" + Class1.IC.ToString() + ";Integrated Security= True;pooling=false;Connection Timeout=0;";
MessageBox.Show("Connection Made!");
this.Close();`(this is for the settings form)

 frmSettings settings = new frmSettings();
                    connectString = frmSettings.connect.ToString();
                    dbconnection = new SqlConnection(connectString);
                    dbconnection.Open(); //<--(and this is where I call the connection string after the set-up)

我该怎么做才能检索用户制作的最后一个连接字符串?有什么建议请帮帮我..

1 个答案:

答案 0 :(得分:0)

我假设您使用的是WinForm。有许多关于保存设置的选项,例如注册表,自定义ini ...等。在去其他地方之前我总是尝试的最简单的一个是配置文件。

添加&#34; System.Configuration&#34;进入你的项目参考。右键单击您的项目&#34;添加新项目&#34;,搜索&#34; config&#34;,您将看到&#34;应用程序配置文件&#34;,添加它。现在你有一个App.Config。

您可以将项目添加到文件中,如:

<?xml version="1.0"?>
<configuration>
<appSettings>
    <add key="Config1" value="Foo" />
    <add key="Config2" value="Bar" />
</appSettings>
</configuration>

要使用它,你可以这样做:

Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var conf = configManager.AppSettings.Settings;
string val1 = conf["Config1"].Value;

您可以使用OpenExeConfiguration调用来查找不同的位置,具体取决于您的YourApp.exe.config文件,但您明白了......