Introduction to Data application in C # read-write operation app.config _c# tutorial

Source: Internet
Author: User
Tags allkeys connectionstrings

Read the statement:

Copy Code code as follows:

String str = configurationmanager.appsettings["Demokey"];

Write statement:
Copy Code code as follows:

Configuration CFA = configurationmanager.openexeconfiguration (Configurationuserlevel.none);
2 CFA. appsettings.settings["Demokey"]. Value = "Demovalue";
3 CFA. Save ();

Configuration file Content format: (app.config)
Copy Code code as follows:

system.configuration.configurationsettings.appsettings["Key"];

system.configuration.configurationsettings.appsettings["Key"];
But now FrameWork2.0 has made it clear that this attribute is obsolete. It was suggested that the change be ConfigurationManager or WebConfigurationManager. And the AppSettings property is read-only and does not support modifying property values.

However, to invoke ConfigurationManager you must first add a System.Configuration.dll assembly reference to the project. (Right-click the project name in Solution Manager and select Add Reference in the right menu to be found under. NET Tablepage) you can use String str = configurationmanager.appsettings["Key" after adding a reference To get the corresponding value.

Update configuration file:
Configuration CFA = configurationmanager.openexeconfiguration (Configurationuserlevel.none);
CfA. APPSETTINGS.SETTINGS.ADD ("Key", "Name") | | CfA. appsettings.settings["Browsedir"]. Value = "name";

Last Call
CfA. Save ();
The current profile update was successful.

Read and write configuration file app.config
A configuration file is provided in. NET so that we can handle configuration information in an important way, which is in XML format. And. NET has already provided some functionality to access this file.

1. Read configuration information
The details of a configuration file are as follows:
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<appSettings>
<add key= "connenctionstring" value= "*"/>
<add key= "Tmppath" value= "C:\Temp"/>
</appSettings>
</configuration>

. NET provides a way to directly access the <appsettings> (note case) element, in which there are a number of child elements, the names of which are "add" and two attributes are "key" and "value" respectively. In general, we can write our own configuration information in this area, through the following ways to access:

String constring=system.configuration.configurationsettings.appsettings["connenctionstring"];

After the appsettings is the value of the key property of the child element, such as appsettings["connenctionstring"], we are accessing <add key= "connenctionstring" value= "*"/ > This child element, its return value is "*", that is, the Value property.

2. Set Configuration information
If the configuration information is static, we can manually configure it to pay attention to the format. If the configuration information is dynamic, we need to write a program to implement it. Without the ability to write profiles in. NET, we can manipulate the configuration file by manipulating the XML file. The following is an example of a write configuration file.
Copy Code code as follows:

private void Saveconfig (string connenctionstring)
{
XmlDocument doc=new XmlDocument ();
Get the full path to the configuration file
String strfilename=appdomain.currentdomain.basedirectory.tostring () + "Code.exe.config";
Doc. LOAd (strFileName);
Find all elements with the name "add"
XmlNodeList Nodes=doc. getElementsByTagName ("add");
for (int i=0;i<nodes. count;i++)
{
Gets the key property of the current element
XmlAttribute Att=nodes[i]. attributes["Key"];
Determines whether the current element is a target element based on the first property of the element
if (Att. value== "ConnectionString")
{
Assign a value to the second property in the target element
Att=nodes[i]. attributes["value"];
Att. value=connenctionstring;
Break
}
}
Save the changes above
Doc. Save (strFileName);
}

Read and write configuration file in VS2005

VS2003 provides read-only functionality for application configuration files (app.config or web.config). In VS2005, the function of the configuration file has been greatly enhanced. In VS2005, Configuration,configurationmanager Two classes are commonly used for reading and writing to application configuration files. The ConfigurationManager class provides a feature of access to client applications. When you use the ConfigurationManager object to perform an operation that opens a configuration file, a configuration object is returned. The code for implementing a read-write configuration file through a program is as follows:

1. Create the class that corresponds to the configuration section in the configuration file. The class must inherit from the ConfigurationSection
Copy Code code as follows:

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

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 resulting configuration file format looks like this:
Copy Code code 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
Copy Code code as follows:

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

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 "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 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. In the Declarations section use <section 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:

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

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:
Here is the code to access this configuration section group:
Copy Code code as follows:

NameValueCollection nc= (NameValueCollection) configurationsettings.getconfig ("Testgroup/test");
MessageBox.Show (NC. Allkeys[0]. ToString () + "" +nc["Hello"]); Output Hello World

Configure App.config


1. Add app.config files to the project:

Right-click the project name, select Add → add new item, and in the Add New Item dialog box that appears, select Add application configuration file, or if the project does not have a profile previously, 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 project has been compiled, under the Bin\debuge file, there will be two profiles (take this project as an example), one named "JxcManagement.EXE.config" and the other named "JxcManagement.vshost.exe.config ”。 The first file is the configuration file that is actually used by the project, and changes made in the running of the program are saved here, and the second file is the original code "app.config" synchronization file that will not change in the program's operation.

2. ConnectionStrings configuration section:

Please note that if your SQL version is in the "localhost\sqlexpress" version, the default installation is a SQL Server instance named "Data Source=localhost", which you must change in the following instance One sentence is "Data source=localhost\sqlexpress;" And do not add a space on either side of the equals number.

<!--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 configured for the entire program, and if it is configured for the current user, use the UserSettings configuration section in the same format as the following configuration writing requirements.
Copy Code code as follows:

<!--inventory management system initialization required parameters-->
<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 also add a reference to System.Configuration.dll in the project, in addition to adding a reference system.configuration.

4.1 Read connectionstrings configuration section

<summary>
ConnectionName return data connection string based on connection string name
Copy Code code as follows:

</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 connectionstrings configuration section
Copy Code code as follows:

<summary>
Update connection string
</summary>
<param > Connection string name </param>
<param > Connection string Content </param>
<param > Data Provider name </param>
private static void Updateconnectionstringsconfig (String newName, String newconstring, String newprovidername)
{
BOOL ismodified = false; Log whether the connection string already exists
If the connection string you want to change already exists
if (Configurationmanager.connectionstrings[newname]!= null)
{
IsModified = true;
}
Create a new connection string instance
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, delete it first
if (ismodified)
{
Config. ConnectionStrings.ConnectionStrings.Remove (NewName);
}
Adds a new connection string to the configuration file.
Config. CONNECTIONSTRINGS.CONNECTIONSTRINGS.ADD (mysettings);
To save changes to a configuration file
Config. Save (configurationsavemode.modified);
Force the connectionstrings configuration section of the configuration file to be loaded again
Configurationmanager.refreshsection ("connectionstrings");
}

4.3 Read appstrings configuration section
Copy Code code as follows:

<summary>
Returns the value entry for the appsettings configuration section in the *.exe.config file
</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 connectionstrings configuration section
Copy Code code as follows:

<summary>
Add a pair of keys, value pairs to the appsettings configuration section in the *.exe.config file
</summary>
<param ></param>
<param ></param>
private static void Updateappconfig (String newKey, String newvalue)
{
BOOL ismodified = false;
foreach (string key in Configurationmanager.appsettings)
{
if (Key==newkey)
{
IsModified = true;
}
}

Open App.config of executable
Configuration config =
Configurationmanager.openexeconfiguration (Configurationuserlevel.none);
You are need to remove the "old" settings object before you can replace it
if (ismodified)
{
Config. AppSettings.Settings.Remove (NewKey);
}
ADD an application Setting.
Config. APPSETTINGS.SETTINGS.ADD (Newkey,newvalue);
Save the changes in app.config file.
Config. Save (configurationsavemode.modified);
Force a reload of a changed section.
Configurationmanager.refreshsection ("appSettings");
}

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.