以编程方式改变c#中的连接字符串
本文关键字:连接 字符串 编程 方式 改变 | 更新日期: 2023-09-27 17:53:41
我需要在我的系统中进行连接设置(在运行时更改连接字符串)。我的意思是用户可以设置和连接到任何他们想要的服务器。我的问题是,我如何检索用户在连接设置中所做的最后一个连接字符串,并在用户重新运行程序时使用它?
到目前为止,这是我所做的:
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)
我该怎么做才能检索用户最后创建的连接字符串?
我假设您使用的是WinForm。有许多保存设置的选项,如注册表,自定义ini…等。在去其他地方之前,我总是尝试最简单的配置文件。
添加"系统。配置"到您的项目参考中。右键单击您的项目和"添加新项目",搜索"配置",您将看到"应用程序配置文件",添加它。现在你有了一个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;
您可以使用openexecconfiguration调用来根据您的YourApp.exe.config文件查找不同的位置,但是您得到了这个想法…