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

以编程方式更改C#中的连接字符串,c#,connection-string,C#,Connection String,我需要在系统中设置连接(在运行时更改连接字符串)。我的意思是用户可以设置并连接到他们想要的任何服务器。我的问题是,如何检索用户在连接设置中创建的最后一个连接字符串,并在用户重新运行程序时使用它 到目前为止,我所做的是: connect = "Data Source=" + Class1.DS.ToString() + ";Initial Catalog=" + Class1.IC.ToString() + ";Integrated Security= True;pooling=false;Con

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

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

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)
connect=“Data Source=“+Class1.DS.ToString()+”;Initial Catalog=“+Class1.IC.ToString()+”;集成安全性=True;池=false;连接超时=0;
MessageBox.Show(“建立连接!”);
这个。关闭()`(这是用于设置表单)
frmSettings设置=新frmSettings();
connectString=frmSettings.connect.ToString();
dbconnection=新的SqlConnection(connectString);

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

将“System.Configuration”添加到项目参考中。右键单击您的项目并“添加新项目”,搜索“配置”,您将看到“应用程序配置文件”,添加它。现在你有了App.Config

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

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

根据YourApp.exe.config文件的不同,您可以使用OpenExeConfiguration调用来查找不同的位置,但是您得到了这样的想法…

假设您仅限于SQL Server,您应该查看SqlConnectionStringBuilder类:@grantwiney用户只放置数据源(服务器名称)和初始目录(数据库名称) .. 他们正在文本框中输入值。我建议您使用UDL文件;)。@GrantWinney先生你能告诉我怎么做吗?我想到了很多想法;一种是将用户设置存储在本地数据库中。如果愿意,您还可以存储连接历史记录,允许用户选择任何最近的连接。我需要在运行时保存它。。我怎样才能做到?我认为你的建议是硬编码的。@ Qwety,你可以调用COMMANDSOME。SAVER()来保存回XML。@ QWTY请考虑这是一个答案。
Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var conf = configManager.AppSettings.Settings;
string val1 = conf["Config1"].Value;