将数据从文本框存储到appconfig中
本文关键字:appconfig 存储 数据 文本 | 更新日期: 2023-09-27 18:26:52
我有textbox
,其中select
path
用于.txt
,其中保存并编码SqlConnection
的数据:
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:''";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
textBox5.Text = string.Format("{0}", openFileDialog1.FileName) ;
// here I need some miracle to save default text for textBox5, appconfig maybe? according to which path was selected
nacti_spojeni();
}
但问题是,用户每次想要连接到SQL数据库时都必须选择路径,我想如果可能的话,有办法将路径保存到应用程序配置中吗?我想到的其他事情是为textbox设置默认文本值。也许这是一个琐碎而无意义的问题。谢谢大家抽出时间。
您可以使用从txt框传递的路径值更新配置文件,如下所示,
注意:当您在visualstudio中以调试模式测试此方法时,您将看到只有AppConfig.vshost.exe.config
会在传递值的情况下更新。
private static void UpdateConnectionString(string path)
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings["ConfigurationKeyForPath"].Value = path;
//Save only the modified section of the config
configuration.Save(ConfigurationSaveMode.Modified);
//Refresh the appSettings section to reflect updated configurations
ConfigurationManager.RefreshSection("appSettings");
}
我根本不建议将用户输入保存在app.config中。这不是该文件的目的。它用于作为开发人员或操作员配置应用程序。如果数据库设置是由用户提供的(我认为这是管理员-不是任何用户都可以更改应用程序的数据库设置…),则可以将它们存储在数据库中或不同于app.config的文件中。