Introduction to data application in C read and write operation app.config

  • 2020-05-07 20:18:31
  • OfStack

Read the statements:


String str = ConfigurationManager.AppSettings["DemoKey"];

Write statement:

Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
2 cfa.AppSettings.Settings["DemoKey"].Value = "DemoValue"; 
3 cfa.Save();

Configuration file content format :(app.config)

System.Configuration.ConfigurationSettings.AppSettings["Key"];

System.Configuration.ConfigurationSettings.AppSettings["Key"];
But now FrameWork 2.0 has made it clear that this attribute is obsolete. It is suggested to change to ConfigurationManager or WebConfigurationManager. Also, the AppSettings property is read-only and does not support changing the property value.

However, to invoke ConfigurationManager, you must first add a reference to the system.configuration.dll assembly to the project. (right click on the project name in solution manager and select add reference from the right click menu.net TablePage). After adding reference, you can use String str = ConfigurationManager.AppSettings ["Key"] to get the corresponding value.

Update profile:
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfa. AppSettings. Settings. Add (" key ", "Name") | | cfa. AppSettings. Settings [r]. "BrowseDir Value =" name ";

The last call
cfa.Save();
The current configuration file was updated successfully.

Read and write configuration file app.config
The configuration file is provided in.Net, which allows us to deal with the configuration information in many aspects. This configuration is in XML format. Also, some access to this file is already provided in Net.

1. Read the configuration information
The following is the specific content of a configuration file:

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
<appSettings> 
<add key="ConnenctionString" value="*" /> 
<add key="TmpPath" value="C:\Temp" /> 
</appSettings> 
</configuration>

.net provides direct access < appsettings > Method of the (case) element, in which there are many child elements with the name "add" and two attributes "key" and "value". 1. In general, we can write our configuration information in this area and access it in the following ways:

string ConString=System.Configuration.ConfigurationSettings.AppSettings["ConnenctionString"];

After appsettings is the value of the key attribute of the child element, such as appsettings["connenctionstring"], which we call < add key="ConnenctionString" value="*" / > The return value of this child element is "*", which is the value of the value attribute.

2. Set the configuration information
If the configuration information is static, we can configure it manually, and pay attention to the format. If the configuration information is dynamic, we need to write a program to implement it. There is no function of writing configuration files in.Net, so we can manipulate the configuration files in the same way as XML files. Here is an example of writing a configuration file.

private void SaveConfig(string ConnenctionString) 
{ 
XmlDocument doc=new XmlDocument(); 
// Gets the full path to the configuration file  
string strFileName=AppDomain.CurrentDomain.BaseDirectory.ToString()+"Code.exe.config"; 
doc.LOAd(strFileName); 
// Find fame as" add All the elements of"  
XmlNodeList nodes=doc.GetElementsByTagName("add"); 
for(int i=0;i<nodes.Count;i++) 
{ 
// Gets the current element key attribute  
XmlAttribute att=nodes[i].Attributes["key"]; 
// By the number of elements 1 Attributes to determine whether the current element is the target element  
if (att.Value=="ConnectionString") 
{ 
// To the target element 2 Attribute assignment  
att=nodes[i].Attributes["value"]; 
att.Value=ConnenctionString; 
break; 
} 
} 
// Save the above changes  
doc.Save(strFileName); 
}

Read and write configuration files in VS2005

VS2003 only provides the ability to read application configuration files (app.config or web.config). In VS2005, the configuration file functionality has been greatly enhanced. In VS2005, Configuration and ConfigurationManager classes are used for read-write 1 of application configuration files. The ConfigurationManager class provides 1 access to client applications. After opening the configuration file using the ConfigurationManager object, one Configuration object is returned. The code to read and write the configuration file through the program is as follows:

1. Create the class corresponding to the configuration section in the configuration file. The class must inherit from ConfigurationSection

public sealed class ConfigurationSections : ConfigurationSection 
{ 
[ConfigurationProperty("filename", DefaultValue = "default.txt")] 
public string FileName 
{ 
get 
{ 
return (string)this["filename"]; 
} 
set 
{ 
this["filename"] = value; 
} 
} 
} 
public sealed class BusinessSpaceConfiguration : ConfigurationSection 
{ 
[ConfigurationProperty("filename")] 
public string FileName 
{ 
get 
{ 
return (string)this["filename"]; 
} 
set 
{ 
this["filename"] = value; 
} 
} 
}

2. Create the profile code

private static void WriteAppConfiguration() 
{ 
try 
{ 
ConfigurationSections configData = new ConfigurationSections(); 
configData.FileName = "abc.txt"; 
System.Configuration.Configuration config = 

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
config.Sections.Remove("ConfigurationSections"); 
config.Sections.Add("ConfigurationSections", configData); 
config.Save(); 

BusinessSpaceConfiguration bsconfigData = new BusinessSpaceConfiguration(); 
bsconfigData.FileName = "def.txt"; 
System.Configuration.Configuration config1 = 

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
config1.Sections.Remove("BusinessSpaceConfiguration"); 
config1.Sections.Add("BusinessSpaceConfiguration", bsconfigData); 
config1.Save(); 
} 
catch (Exception err) 
{ 
Console.Write(err.Message); 
} 
}

3. The generated configuration file format is as follows:

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
<configSections> 
<section 

type="ConsoleApplication1.BusinessSpaceConfiguration, ConsoleApplication1, Version=1.0.0.0, 

Culture=neutral, PublicKeyToken=null" /> 
<section type="ConsoleApplication1.ConfigurationSections, 

ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> 
</configSections> 
<BusinessSpaceConfiguration filename="def.txt" /> 
<ConfigurationSections filename="abc.txt" /> 
</configuration>

4. Read the application configuration file

private static void ReadAppConfiguration() 
{ 
ConfigurationSections obj1 = ConfigurationManager.GetSection("ConfigurationSections") 

as ConfigurationSections; 
BusinessSpaceConfiguration obj2 = ConfigurationManager.GetSection 

("BusinessSpaceConfiguration") as BusinessSpaceConfiguration; 
Console.WriteLine(obj1.FileName); 
Console.WriteLine(obj2.FileName); 

}

Custom application configuration file (app.config)
1. Profile overview:
Application configuration files are standard XML files, and 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. We often visit 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 1 node of XML.

Common profile patterns:

<configuration> 
<configSections> // The configuration section declaration area, which contains the configuration section and the namespace declaration  
<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> // Configure section Settings area  

2. Only configuration files and access methods of section appSettings
The following is an example of one of the most common application configuration files, with only section appSettings.

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
<appSettings> 
<add key="connectionstring" value="User 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 files
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 in the configuration section (" < section > "), in addition is in < configSections > < /configSections > Then set up the configuration section (" < Custom element for configuration section > "), which is similar to declaring a variable first and then using one. The statement to declare 1 configuration file is as follows:
< section " type=" "/ >
< section > : declare a new configuration section to create a new configuration section.

name: name of the custom configuration section.
type: custom configuration section type, mainly including System.Configuration.SingleTagSectionHandler, System.Configuration.DictionarySectionHandler, System.Configuration.NameValueSectionHandler.

Different type not only set up the configuration section in the same way, 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 type="System.Configuration.SingleTagSectionHandler"/> 
<section type="System.Configuration.DictionarySectionHandler"/> 
<section 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 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 World, and more. The other two configuration sections are similar to this one.
Let's look at how to access these custom configuration sections in the program. We used the static method GetConfig of the ConfigurationSettings class for 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); // output Hello World

// access method 2 of configuration section Test1
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
From the above code, we can see that different type return different types through GetConfig, and the specific way to obtain 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 > The element declares a configuration section group and places sections belonging to that group < sectionGroup > Element. Here is an example of a configuration file containing a configuration section group:
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"]); // The output Hello World

Configuration App config


1. Add app.config file to the project:

Right-click the project name and select "add" → "add new item". In the "add new item" dialog box, select "add application configuration file". If the project did not have a configuration file before, the default file name is "app.config" and click ok. The app.config file that appears in the designer view is:

< ?xmlversion="1.0"encoding="utf-8" ? >
< configuration >
< /configuration >

After the program compiled under the bin \ Debuge file, will appear two configuration files (in this project, for example), one called "JxcManagement. EXE. config", the other one is called "JxcManagement. vshost. exe. config". The first file is the actual configuration file used by the project, where any changes made during the program run will be saved. The second file is a synchronous file of the original code "app.config", which will not change during the program running.

2. connectionStrings configuration section:

Please note: if your SQL version is 2005 Express, then by default the SQL server instance is localhost\SQLExpress and the following instance must be changed to "Data Source=localhost;" 1 sentence: "Data Source=localhost\SQLExpress;" Don't put a space on either side of the equals sign.

< ! Database connection string >
< connectionStrings >
< clear / >
< addname="conJxcBook" connectionString="Data Source=localhost;Initial Catalog=jxcbook;User providerName="System.Data.SqlClient" / >
< /connectionStrings >

3. appSettings configuration section:

The appSettings configuration section is the configuration of the entire program. If the configuration is for the current user, please use the userSettings configuration section.

<!-- The required parameters are initialized by the invoicing management system --> 
<appSettings> 
<clear /> 
<addkey="userName"value="" /> 
<addkey="password"value="" /> 
<addkey="Department"value="" /> 
<addkey="returnValue"value="" /> 
<addkey="pwdPattern"value="" /> 
<addkey="userPattern"value="" /> 
  </appSettings>

4. Read and update app.config

Note: to access the app.config file using the following code, you must add a reference to System.Configuration.dll in your project, in addition to adding a reference to System.Configuration.

4.1 read the connectionStrings configuration section

/// < summary >
/// returns a data connection string based on the connection string name connectionName

///</summary> 
///<param ></param> 
///<returns></returns> 
private static string GetConnectionStringsConfig(string connectionName) 
{ 
string connectionString = 
ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString(); 
Console.WriteLine(connectionString); 
return connectionString; 
}

4.2 update the connectionStrings configuration section
 
///<summary> 
/// Update connection string  
///</summary> 
///<param > Concatenation string name </param> 
///<param > Concatenate string content </param> 
///<param > Data provider name </param> 
private static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName) 
{ 
bool isModified = false; // Record whether the connection string already exists  
// If the connection string you want to change already exists  
if (ConfigurationManager.ConnectionStrings[newName] != null) 
{ 
isModified = true; 
} 
// new 1 Connection string instances  
ConnectionStringSettings mySettings = 
new ConnectionStringSettings(newName, newConString, newProviderName); 
//  Open the executable configuration file *.exe.config 
Configuration config = 
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
//  If the connection string already exists, remove it first  
if (isModified) 
{ 
config.ConnectionStrings.ConnectionStrings.Remove(newName); 
} 
//  Adds a new connection string to the configuration file . 
config.ConnectionStrings.ConnectionStrings.Add(mySettings); 
//  Save the changes made to the configuration file  
config.Save(ConfigurationSaveMode.Modified); 
//  Forcing a reload of the configuration file ConnectionStrings The configuration section  
ConfigurationManager.RefreshSection("ConnectionStrings"); 
}

4.3 read the appStrings configuration section
 
///<summary> 
/// Return * .exe.config In the file appSettings The configuration section value item  
///</summary> 
///<param ></param> 
///<returns></returns> 
private static string GetAppConfig(string strKey) 
{ 
foreach (string key in ConfigurationManager.AppSettings) 
{ 
if (key == strKey) 
{ 
return ConfigurationManager.AppSettings[strKey]; 
} 
} 
return null; 
}

4.4 update the connectionStrings configuration section

Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
2 cfa.AppSettings.Settings["DemoKey"].Value = "DemoValue"; 
3 cfa.Save();
8


Related articles: