asp.net read configuration file method _ Practical Tips

Source: Internet
Author: User
Tags allkeys
Method 1:
Copy Code code as follows:

System.Collections.Specialized.NameValueCollection NVC = (System.Collections.Specialized.NameValueCollection)
System.Configuration.ConfigurationManager.GetSection (sectionname);

String keyvalue = NVC. GetValues (KeyName) [0]. ToString ();
Method 2:
Copy Code code as follows:
System.web.configuration.webconfigurationmanager.appsettings[keyname]. ToString ();

Refer to the following article

How to read a configuration file in C #
1. configuration file Overview:
The application configuration file is a standard XML file, and XML tags and attributes are case-sensitive. It can be changed as needed, and developers can use the configuration file to change the settings without recompiling the application. The root node of the configuration file is configuration. What we often visit is appsettings, which is made up of. NET predefined configuration section. The configuration file we use often has a schema that looks like the following form. There is probably an impression that there is a clearer understanding of the following examples. The following "configuration section" can be understood as a node for configuring an XML.
Common configuration file Mode:
Copy Code code as follows:

<configuration>
<configSections>//configuration section Declaration area, including configuration sections and namespace declarations
<section>//configuration section statement
<sectionGroup>//Define configuration section Group
Configuration section declarations in <section>//configuration section groups
<appSettings>//Predefined configuration section
<custom element for configuration section>//configuration section Settings area

2. Only appsettings section of the configuration file and Access methods
The following is an example of the most common application configuration file, with only the appsettings section.
Copy Code code as follows:

<?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 look at how this configuration file is done.
String _connectionstring=configurationsettings.appsettings["connectionString"];
You can use the static properties of the ConfigurationSettings class to appsettings the configuration information in the method configuration file directly. The type of this property is NameValueCollection.
3. Custom configuration file
3.1 Custom Configuration section
A user-defined configuration section that is divided into two parts in a configuration file: The first is to declare the configuration section in the <configsections></configsections> configuration section ("<section>" in the configuration file mode above) , in addition to setting the configuration section after < configsections></configsections > ("<custom Element for Configuration" in the configuration file mode above) > "), somewhat similar to a variable declared before use. The statement declaring a configuration file is as follows:
<section name= "" type= ""/>
<section&gt: Declares a new configuration section to create a new configuration section.
Name: Names of custom configuration sections.
Type: The types of custom configuration sections, mainly including System.Configuration.SingleTagSectionHandler, System.Configuration.DictionarySectionHandler, System.Configuration.NameValueSectionHandler.
Different types not only set configuration sections differently, but also have differences in the operation of the last access profile. Here's an example of a configuration file that contains these three different types.
Copy Code code as follows:

<?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. In the Declarations section use <section name= "Test1" type= "System.Configuration.SingleTagSectionHandler"/> declares a configuration section its name is Test1, Type is SingleTagSectionHandler. In the Set configuration section section, use <test1 setting1= "Hello" setting2= "World"/> Set up a configuration section, its first set value is Hello, the second value is world, of course, there can be more. The other two configuration sections are similar to this one.
Here's how you can access these custom configuration sections in your program. We have used the static method GetConfig of the ConfigurationSettings class to get the information for the custom configuration section.
public static Object GetConfig (string sectionname);
Here is the code to access these three configuration sections:
Copy Code code as follows:

Access configuration section Test1
IDictionary IDTest1 = (IDictionary) configurationsettings.getconfig ("Test1");
String str = (string) idtest1["setting1"] + "" + (String) idtest1["Setting2"];
MessageBox.Show (str); Output Hello World
method to access configuration section Test1 2
String[] Values1=new String[idtest1.count];
IDTest1.Values.CopyTo (values1,0);
MessageBox.Show (values1[0]+ "" +values1[1]); 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"]); Output Hello World

We can see from the above code that different types are different from the type returned by GetConfig, and the exact way to get the configuration content is not the same. Configuration section Handlers
return type
Copy Code code as follows:

SingleTagSectionHandler
Systems.Collections.IDictionary
DictionarySectionHandler
Systems.Collections.IDictionary
NameValueSectionHandler
Systems.Collections.Specialized.NameValueCollection

3.2 Custom Configuration section groups
A configuration section group uses the <sectionGroup> element to divide similar configuration sections into the same group. The configuration section Group Declaration section creates the containing element of the configuration section, declares the configuration section group in the <configSections> element, and places the section belonging to the group in the < sectiongroup> element. The following is an example of a configuration file that contains a configuration section group:
Copy Code code as follows:

<?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 this configuration section group:
NameValueCollection nc= (NameValueCollection) configurationsettings.getconfig ("Testgroup/test");
MessageBox.Show (NC. Allkeys[0]. ToString () + "" +nc["Hello"]); Output Hello World
C # Parsing configuration file content System.Configuration
1. Create a configuration section class
You must create an object that inherits from ConfigurationSection for configuration data read and write operations, ConfigurationSection provides indexers for obtaining and setting configuration data. It is important to note that properties that have the ConfigurationProperty attribute are stored, and that the name is kept exactly the same case, as in the following code, all "IDs" must remain the same.
Copy Code code as follows:

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 a Profile Action object
Copy Code code as follows:

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 with the name "Add" under the root node (configuration).
Copy Code code as follows:

<?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 then overwrite the file when the program closes, so you may not see the configuration data that you write, as long as the *.exe file is executed in resource management, you can do it in the *. The results are seen in the Exe.config file.
If we need to manipulate a non-default profile, we can use the Execonfigurationfilemap object.
Copy Code code as follows:

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 do not want to write configuration data under the root node, we can use the ConfigurationSectionGroup object.
Copy Code code as follows:

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 following is the generated configuration file.
Copy Code code as follows:

<?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
Copy Code code as follows:

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 root section
if (data!= null)
{
Console.WriteLine (data. ID);
Console.WriteLine (data. Time);
}

4. Write Configuration file
To determine whether a configuration with the same name already exists before writing ConfigurationSectionGroup and ConfigurationSection, failure is written.
In addition, if the configuration file is modified by another configuration object, the save fails and throws an exception. It is recommended to adopt Singleton mode.
Copy Code code as follows:

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 modify the original configuration object directly, if the type conversion is successful.
Configsectiondata ConfigData = add as Configsectiondata;
configdata.id = data. Id;
Configdata.time = data. time;
}
Config. Save (Configurationsavemode.minimal);

5. Delete configuration section
Copy Code code as follows:

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 Machine.config files.
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 operation.
7. Using Custom Classes
You can use custom classes, but you need to define a converter.
Copy Code code as follows:

Using System;
Using System.Collections;
Using System.Collections.Generic;
Using System.Configuration;
Using System.Globalization;
Using System.ComponentModel;
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 Converters (Demo code omits type judgments)
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 Test
Configsectiondata ConfigData = (configsectiondata) config. sections["Add"];
Console.WriteLine (CONFIGDATA.CUSTOM.S);
}
}

Saved configuration file
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<configSections>
<section name= "Add" type= "..."/>
</configSections>
<add id= "1000" time= "04/17/2006 22:06:58" custom= ... "ABCDEFG
</configuration>

More detailed information can be seen in the MSDN instructions on System.Configuration.ConfigurationConverterBase.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.