2

我在textbox其中保存和编码数据:select path.txtSqlConnection

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

4

2 回答 2

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");           
}
于 2013-08-07T10:52:06.820 回答
2

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

于 2013-08-07T09:56:23.523 回答