从文本框中将数据存储到appconfig中 [英] Storing data into appconfig from textbox

查看:92
本文介绍了从文本框中将数据存储到appconfig中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有textbox,其中保存了.txt的I select path,并存储了SqlConnection的编码数据:

I have textbox in which I select path for .txt, in it are saved and encoded data for 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数据库时都必须选择路径,我想如果可以的话,可以将路径保存到应用程序配置中吗?我想到的其他事情是为文本框设置默认文本值.也许这是一个琐碎且毫无意义的问题.谢谢大家的时间.

But the issue is that the user have to select path each time he wants to connect to SQL Database, I thought there could be way to save the path into app config if it is possible? Other things that comes to my mind is to set default text value for textbox. Maybe this is trivial and non-sense question. Thank you all for your time.

推荐答案

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

You can update the configuration file with the path value passed from txt box as follows,

注意:当您在Visual Studio中以调试模式测试此方法时,只会看到AppConfig.vshost.exe.config会被更新,而不会传递值.

Note : When you test this method in debug mode in visual studio you will see only AppConfig.vshost.exe.config will be updated witht the value passed.

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");           
}

这篇关于从文本框中将数据存储到appconfig中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆