【发布时间】:2013-07-31 12:27:21
【问题描述】:
这是我的第一个问题,也是我的第一个 C# 程序:
我需要可以永久更改连接字符串的函数。
我的程序有这样的结构:
主表单是Form1,当我单击按钮时,Options,我从 - Form3 获取新表单,用户可以登录(密码保护更改选项),如果登录成功,我创建新表单 - Form4 .在Form4 的构造函数中,我从Form1 传递了一个SqlConnection 对象。我想通过单击按钮更改我的数据库名称,所以这里是代码:
var config = ConfigurationManager
.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config
.GetSection("connectionStrings");
var x = connectionStringsSection
.ConnectionStrings["App.Properties.Settings.ppsConnectionString"]
.ConnectionString;
String[] words = x.Split(';');
words[1] = "Initial Catalog="+textBoxDB.Text;
x=String.Join(";", words);
connectionStringsSection
.ConnectionStrings["App.Properties.Settings.ppsConnectionString"]
.ConnectionString = x;
//above, this variable x in debug mode looks right
//I read this line below should update file, so change would be permamently
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
但它不会改变任何东西,我不知道如何更改此设置文件,以便用户可以更改数据库名称,当他们重新启动应用程序时,他们应该有这个新的更改连接字符串。
编辑:
感谢您的回复,事实证明我应该从 bin/Release .exe 版本运行此代码,而不是在 VS 中的 Debug 下运行,它实际上更改了此配置文件。
【问题讨论】:
-
重复 - stackoverflow.com/questions/3838027/… - 实际上,谷歌搜索会显示大量关于如何从 C# 更新配置文件的结果。
-
嗯,我没有看到 cmets,有一个棘手的细节
标签: c# winforms connection-string