从textbox将数据存储到appconfig中

时间:2013-08-07 09:38:31

标签: c# sql sql-server winforms app-config

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数据库时都必须选择路径,我想如果有可能的话可以将路径保存到app config中?我想到的其他事情是为文本框设置默认文本值。也许这是微不足道和无意义的问题。谢谢大家的时间。

2 个答案:

答案 0 :(得分:2)

我根本不建议在app.config中保存用户输入。这不是文件的目的。它用作开发人员或操作员来配置您的应用程序。如果数据库设置由用户提供(我假设这是管理员 - 并非任何用户都应该能够更改应用程序的数据库设置...),则可以将它们存储在数据库或不同于应用程序的文件中。配置。

答案 1 :(得分:2)

您可以使用从txt框传递的路径值更新配置文件,如下所示,

注意:在Visual Studio中以调试模式测试此方法时,您将看到只有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");           
}