问题描述:

So I have been poking around both here on SO and google for the last few days for information about app.config.

I am writing a program that will need to generate SQL scripts using values entered by a user. Originally I was using app.config to store some default values to load into the program when it is first started up. This worked fine until I tried to store the new values back into the app.config file. This is when I found that app.config is read only and I should have been using user.config.

I have several questions that I can't seem to find the answers to:

  1. Is it recommended to use settings.Setting to declare all the values that I want to use app.config? Or is entering them in by hand is enough?

  2. I keep reading about how user.config overrides app.config settings. But when I update my user.config file, the program still reads from the original app.config file

This is from my wrapper class

public NameValueCollection ReadSettings(string sectionName)

{

NameValueCollection scripts = null;

try

{

//read in the current values from the section

scripts = (NameValueCollection)ConfigurationManager.GetSection(sectionName);

if (scripts == null) throw new appConfigException(String.Format("The section {0} does not exists in app.config", sectionName));

}catch (Exception e){

//print out the log file

StreamWriter writer = new StreamWriter(DateTime.Now.ToString("d-MMM-yyyy") + "log.txt");

writer.WriteLine(e.ToString());

writer.Close();

//kill the application process so the user cannot advance further

System.Diagnostics.Process.GetCurrentProcess().Kill();

}

return scripts;

}

is the ConfigurationManager supposed to automatically know to start reading from the user.config? Or do I need to change this section of code to reflect that?

网友答案:

Question 1: It is easier to use Settings.settings instead of creating your own configuration file yourApp.config. Because using the first option you can access your properties just using Properties.Settings.Default.MyProperty and with the app.config file instead you have to deal with ConfigurationManager object, and usually to access a property you need to know the name beforehand and it usually is hardcoded.

Question 2: Yes, you are right the app.config is different from Settings.setting. Because you could even create a new file temp.config which could also be used as a config file for your application.

Final question: Im not sure, but I don't think ConfigurationManager knows anything about that, just parse the app.config file.

Hope it helps.

相关阅读:
Top