问题
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();
}
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.
回答1:
You can update the configuration file with the path value passed from txt box as follows,
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");
}
回答2:
I do not recommend at all to save user input in the app.config. This is not the purpose of the file. It is used for you as a developer or an operator to configure your application. If the database settings are provided by a user (I presume this is an administrator - not any user should be able to change database settings of your application...) you can store them in a database or in a file different than the app.config.
来源:https://stackoverflow.com/questions/18099910/storing-data-into-appconfig-from-textbox