asp.net reads the configuration file method

  • 2020-05-16 06:44:35
  • OfStack

Method 1:
 
System.Collections.Specialized.NameValueCollection nvc = (System.Collections.Specialized.NameValueCollection) 
System.Configuration.ConfigurationManager.GetSection(sectionName); 

string keyValue = nvc.GetValues(keyName)[0].ToString();
Method 2:
System.Web.Configuration.WebConfigurationManager.AppSettings[keyName].ToString(); 

Refer to the article below

How do I read a configuration file in C#
1. Profile overview:
The program configuration file should be the standard XML file, and the XML tags and attributes are case sensitive. It can be changed as needed, and developers can use configuration files to change Settings without having to recompile the application. The root node of the configuration file is configuration. The one we often visit is appSettings, which is a predefined configuration section by.Net. The configuration file architecture we often use is in the form of the following. First there is an impression, through the following example will have a more clear understanding. The following "configuration section" can be interpreted as configuring one XML node.
Common profile patterns:
 
<configuration> 
<configSections> // The configuration section declaration area, which contains the configuration section and namespace declarations  
<section> // Configuration section declaration  
  <sectionGroup> // Define the configuration section group  
   <section> // Configuration section declaration in the configuration section group  
<appSettings> // Predefined configuration section  
<Custom element for configuration section> // The configuration section sets up the area  

2. Only the configuration files and access methods of section appSettings
Here is an example of one of the most common application configuration files, with only the appSettings section.
 
<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
<appSettings> 
<add key="connectionstring" value="User ID=sa;Data Source=.;Password=;Initial Catalog=test;Provider=SQLOLEDB.1;" /> 
<add key="TemplatePATH" value="Template" /> 
</appSettings> 
</configuration> 

Let's take a look at how such a configuration file works.
string _connectionString=ConfigurationSettings.AppSettings["connectionstring"];
You can use the static property AppSettings of the ConfigurationSettings class to direct the configuration information in the method configuration file. The type of this property is NameValueCollection.
3. Custom configuration file
3.1 custom configuration section
1 user-defined configuration section, divided into two parts in the configuration file: 1 is in the < configSections > < / configSections > Declare the configuration section (" < section > "), in addition is in < configSections > < / configSections > Then set the configuration section (" < Custom element for configuration section > "), which is similar to declaring a variable first and then using one. The statement to declare a configuration file is as follows:
< section name=" " type=" "/ >
< section > : declare a new configuration section to create a new configuration section.
name: name of the custom configuration section.
type: types of custom configuration sections, including System.Configuration.SingleTagSectionHandler, System.Configuration.DictionarySectionHandler, System.Configuration.NameValueSectionHandler.
Different type not only set up the configuration section in different ways, but also have different access to the configuration file. Let's take an example of a configuration file that contains three different type.
 
<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
<configSections> 
<section name="Test1" type="System.Configuration.SingleTagSectionHandler"/> 
<section name="Test2" type="System.Configuration.DictionarySectionHandler"/> 
<section name="Test3" type="System.Configuration.NameValueSectionHandler" /> 
</configSections> 
<Test1 setting1="Hello" setting2="World"/> 
<Test2> 
<add key="Hello" value="World" /> 
</Test2> 
<Test3> 
<add key="Hello" value="World" /> 
</Test3> 
</configuration> 

We describe the custom configuration section above. Used in the declaration section < section name="Test1" type="System.Configuration.SingleTagSectionHandler"/ > A configuration section is declared with the name Test1 and the type SingleTagSectionHandler. Used in the Settings configuration section < Test1 setting1="Hello" setting2="World"/ > A configuration section is set with the first setting value Hello, the second value World, and more. The other two are similar to this one.
Let's look at how to access these custom configuration sections in your application. We used the static method GetConfig of the ConfigurationSettings class to get information about the custom configuration section.
public static object GetConfig(string sectionName);
Here is the code to access the three configuration sections:
 
// Access configuration section Test1 
IDictionary IDTest1 = (IDictionary)ConfigurationSettings.GetConfig("Test1"); 
string str = (string)IDTest1["setting1"] +" "+(string)IDTest1["setting2"]; 
MessageBox.Show(str); // The output Hello World 
// Access configuration section Test1 The method of 2 
string[] values1=new string[IDTest1.Count]; 
IDTest1.Values.CopyTo(values1,0); 
MessageBox.Show(values1[0]+" "+values1[1]); // The output Hello World 
// Access configuration section Test2 
IDictionary IDTest2 = (IDictionary)ConfigurationSettings.GetConfig("Test2"); 
string[] keys=new string[IDTest2.Keys.Count]; 
string[] values=new string[IDTest2.Keys.Count]; 
IDTest2.Keys.CopyTo(keys,0); 
IDTest2.Values.CopyTo(values,0); 
MessageBox.Show(keys[0]+" "+values[0]); 
// Access configuration section Test3 
NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("Test3"); 
MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]); // The output Hello World 

From the above code, we can see that different type return different types through GetConfig, and the specific way to get the configuration content is not the same. Configure the section handler
The return type
 
SingleTagSectionHandler 
Systems.Collections.IDictionary 
DictionarySectionHandler 
Systems.Collections.IDictionary 
NameValueSectionHandler 
Systems.Collections.Specialized.NameValueCollection 

3.2 custom configuration section group
Configuration section groups are used < sectionGroup > Element, grouping similar configuration sections into the same group. The configuration section group declaration section will create the include elements of the configuration section in the < configSections > A configuration section group is declared in the element and sections belonging to that group are placed < sectionGroup > Element. Here is an example of a configuration file containing a configuration section group:
 
<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
<configSections> 
<sectionGroup name="TestGroup"> 
<section name="Test" type="System.Configuration.NameValueSectionHandler"/> 
</sectionGroup> 
</configSections> 
<TestGroup> 
<Test> 
<add key="Hello" value="World"/> 
</Test> 
</TestGroup> 
</configuration> 

Here is the code to access the configuration section group:
NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("TestGroup/Test");
MessageBox. Show (nc AllKeys [0]. ToString () + "" + nc [" Hello]"); // output Hello World
C# parses the contents of the configuration file System.Configuration
1. Create the configuration section class
You must create objects inherited from ConfigurationSection to read and write configuration data. ConfigurationSection provides indexers to get and set configuration data. It is important to note that properties with ConfigurationProperty properties are stored and the names are kept uppercase.
 
class ConfigSectionData : ConfigurationSection 
{ 
[ConfigurationProperty("id")] 
public int Id 
{ 
get { return (int)this["id"]; } 
set { this["id"] = value; } 
} 
[ConfigurationProperty("time")] 
public DateTime Time 
{ 
get { return (DateTime)this["time"]; } 
set { this["time"] = value; } 
} 
} 

2. Create configuration file action object
 
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
ConfigSectionData data = new ConfigSectionData(); 
data.Id = 1000; 
data.Time = DateTime.Now; 
config.Sections.Add("add", data); 
config.Save(ConfigurationSaveMode.Minimal); 

The example above is the operation app.config, which writes the configuration data named "add" under the root node (configuration).
 
<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
<configSections> 
<section name="add" type="ConsoleApplication1.ConfigSectionData, ... /> 
</configSections> 
<add id="1000" time="02/18/2006 21:51:06" /> 
</configuration> 

Note that VS2005 writes information to *.vshost.exe.config in IDE mode and overrides the file when the program is closed, so you may not see the configuration data you wrote, just execute the *.exe file in resource management and you will see the results in the *.exe.config file.
If we need to operate on a non-default configuration file, we can use the ExeConfigurationFileMap object.
 
ExeConfigurationFileMap file = new ExeConfigurationFileMap(); 
file.ExeConfigFilename = "test.config"; 
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None); 
ConfigSectionData data = new ConfigSectionData(); 
data.Id = 1000; 
data.Time = DateTime.Now; 
config.Sections.Add("add", data); 
config.Save(ConfigurationSaveMode.Minimal); 

If we don't want to write configuration data under the root node, we can use the ConfigurationSectionGroup object.
 
ExeConfigurationFileMap file = new ExeConfigurationFileMap(); 
file.ExeConfigFilename = "test.config"; 
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None); 
ConfigSectionData data = new ConfigSectionData(); 
data.Id = 1000; 
data.Time = DateTime.Now; 
config.SectionGroups.Add("group1", new ConfigurationSectionGroup()); 
config.SectionGroups["group1"].Sections.Add("add", data); 
config.Save(ConfigurationSaveMode.Minimal); 

The resulting configuration file is shown below.
 
<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
<configSections> 
<sectionGroup name="group1" type="System.Configuration.ConfigurationSectionGroup, ... > 
<section name="add" type="ConsoleApplication1.ConfigSectionData, ... /> 
</sectionGroup> 
</configSections> 
<group1> 
<add id="1000" time="02/18/2006 22:01:02" /> 
</group1> 
</configuration> 

3. Read the configuration file
 
ExeConfigurationFileMap file = new ExeConfigurationFileMap(); 
file.ExeConfigFilename = "test.config"; 
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None); 
ConfigSectionData data = config.SectionGroups["group1"].Sections["add"] as ConfigSectionData; 
//ConfigSectionData data = config.Sections["add"] as ConfigSectionData; //  Read from the root node  
if (data != null) 
{ 
Console.WriteLine(data.Id); 
Console.WriteLine(data.Time); 
} 

4. Write configuration files
Before writing ConfigurationSectionGroup and ConfigurationSection, determine if the configuration with the same name already exists, otherwise the write will fail.
In addition, if the configuration file is modified by another Configuration object, the save will fail and an exception will be thrown. Singleton mode is recommended.
 
ExeConfigurationFileMap file = new ExeConfigurationFileMap(); 
file.ExeConfigFilename = "test.config"; 
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None); 
ConfigSectionData data = new ConfigSectionData(); 
data.Id = 2000; 
data.Time = DateTime.Now; 
ConfigurationSectionGroup group1 = config.SectionGroups["group1"]; 
if (group1 == null) 
config.SectionGroups.Add("group1", new ConfigurationSectionGroup()); 
ConfigurationSection data = group1.Sections["add"] as config; 
if (add == null) 
config.SectionGroups["group1"].Sections.Add("add", data); 
else 
{ 
group1.Sections.Remove("add"); 
group1.Sections.Add("add", data); 
//  Or simply modify the original configuration object if the conversion is successful.  
//ConfigSectionData configData = add as ConfigSectionData; 
//configData.Id = data.Id; 
//configData.Time = data.Time; 
} 
config.Save(ConfigurationSaveMode.Minimal); 

5. Delete the configuration section
 
 delete ConfigurationSectionGroup 
config.SectionGroups.Remove("group1"); 
//config.SectionGroups.Clear(); 
config.Save(ConfigurationSaveMode.Minimal); 
 delete ConfigurationSection 
config.Sections.Remove("add1"); 
//config.Sections.Clear(); 
if (config.SectionGroups["group1"] != null) 
{ 
config.SectionGroups["group1"].Sections.Remove("add2"); 
//config.SectionGroups["group1"].Sections.Clear(); 
} 
config.Save(ConfigurationSaveMode.Minimal); 

6. Other
You can use ConfigurationManager.OpenMachineConfiguration () to manipulate the Machine.config file.
Or use the WebConfigurationManager class in the System.Web.Configuration namespace to manipulate the ASP.net configuration file.
ConfigurationManager also provides AppSettings, ConnectionStrings, GetSection() and other convenient operations.
7. Use custom classes
You can use a custom class, but you need to define one converter.
 
using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Configuration; 
using System.Globalization; 
using System.ComponentModel; 
//  The custom class to write to the configuration file  
class CustomData 
{ 
public CustomData(string s) 
{ 
this.s = s; 
} 
private string s; 
public string S 
{ 
get { return s; } 
set { s = value; } 
} 
} 
//  Custom converter ( The demo code omits type determination ) 
class CustomConvert : ConfigurationConverterBase 
{ 
public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type) 
{ 
return (type == typeof(string)); 
} 
public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) 
{ 
return (value as CustomData).S; 
} 
public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) 
{ 
return new CustomData((string)data);; 
} 
} 
class ConfigSectionData : ConfigurationSection 
{ 
[ConfigurationProperty("id")] 
public int Id 
{ 
get { return (int)this["id"]; } 
set { this["id"] = value; } 
} 
[ConfigurationProperty("time")] 
public DateTime Time 
{ 
get { return (DateTime)this["time"]; } 
set { this["time"] = value; } 
} 
[ConfigurationProperty("custom")] 
[TypeConverter(typeof(CustomConvert))] //  Specify converter  
public CustomData Custom 
{ 
get { return (CustomData)this["custom"]; } 
set { this["custom"] = value; } 
} 
} 
public class Program 
{ 
static void Main(string[] args) 
{ 
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
ConfigSectionData data = new ConfigSectionData(); 
data.Id = 1000; 
data.Time = DateTime.Now; 
data.Custom = new CustomData("abcdefg..."); 
config.Sections.Add("add", data); 
config.Save(ConfigurationSaveMode.Minimal); 
//  Read the test  
ConfigSectionData configData = (ConfigSectionData)config.Sections["add"]; 
Console.WriteLine(configData.Custom.S); 
} 
} 

Save the configuration file
System.Web.Configuration.WebConfigurationManager.AppSettings[keyName].ToString(); 
8
For more information, see MSDN's description of System.Configuration.ConfigurationConverterBase.

Related articles: