【问题标题】:Storing data into appconfig from textbox将数据从文本框存储到 appconfig
【发布时间】:2013-08-08 14:59:09
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您可以使用从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");           
    }
    

    【讨论】:

    • 请问我应该提供什么“使用”?
    • 首先你必须添加对 System.Configuration 的引用
    • 添加 using 语句应为“using System.Configuration;”
    • 感谢您抽出宝贵时间,但当前上下文中不存在 Constans。
    • 我试过了,但我不确定到底是什么?请给我简要的信息好吗?我会很高兴的。
    【解决方案2】:

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

    【讨论】:

    • 感谢您的宝贵时间,但问题是我需要记住某人的路径,这可能吗?
    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 2015-03-03
    • 1970-01-01
    相关资源
    最近更新 更多