C # Various configuration files use, summary of how to operate

Source: Internet
Author: User
Tags allkeys dotnet connectionstrings

configuration file Actions

Profiles are generally divided into built-in configuration files and user-defined profiles.

Built-in configuration files include app.config, web.config, settings.settings, and so on.

User-defined profiles typically place configuration information in an XML file or registry, and configuration information typically includes program settings, records running information, and saves information about the control (such as location, style).

one, built-in profile actions

App.config and web.config operations are similar, taking app.config as an example, settings.settings can specify the type and range of values.

1. App.config file Operations

The main nodes in this configuration file are: connectionstrings, appSettings, configsections, etc., these are commonly used, the operation is slightly different, dotnet provide direct operation of each node method. A reference to add a System.Configuration.dll assembly when ConfigurationManager is used.

Changes to the configuration file after the program is migrated are saved in the. exe.config file, but according to my experience if you do not modify the configuration file, General EXE does not automatically create a. exe.config file.

After the project has been compiled, there will be two profiles, one named *, under the Bin\debuge file. Exe.config ", another name is" *.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.

L connectionstrings: Because the data connection string is saved.

Read:

configurationmanager.connectionstrings["Accessdb"]. ConnectionString;

Write:

Set the connection string

connectionstringsettings setconnstr = newconnectionstringsettings ("Accessdb", ConnectionString, " System.Data.OleDb ");

Open the app.config file for the current application to operate

Configuration AppConfig =configurationmanager.openexeconfiguration ( Configurationuserlevel.none);

Because there is no way to update the connection string, add a connection string

AppConfig.ConnectionStrings.ConnectionStrings.Add (SETCONNSTR) directly here

; Appconfig.save ();

Forces the connectionstrings configuration section of the configuration file to reload

configurationmanager.refreshsection ("connectionstrings");

L appSettings: Main stored program settings, in the form of key-value pairs.

Read:

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

Write:

Configuration cfg=configurationmanager.openexeconfiguration (configurationuserlevel.none);

Cfg. appsettings.settings["Demokey"]. Value= "Demovalue";

Cfg. Save ();

L configsections: Custom configuration section

Name: Names of custom configuration sections.

Type: The types of custom configuration sections, mainly include:

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.

Three different type operations:

<?xmlversion= "1.0" encoding= "Utf-8"?>

<configuration>

     <configSections>

         < Sectiontype= "System.Configuration.SingleTagSectionHandler"/>

         <sectiontype= " System.Configuration.DictionarySectionHandler "/>

         <sectiontype=" System.Configuration.NameValueSectionHandler "/>

     </configSections>

     <test1 setting1=" Hello " setting2= "World"/>

     <Test2>

         <add key= "Hello" value= "World"/>

     </Test2>

     < test3>

         <add key= "Hello" value= "World"/>

     </Test3>   

</configuration>


Description: In the Declarations section use <sectiontype= "System.Configuration.SingleTagSectionHandler"/> Declare 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.

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 configuration section Test1 Method 2

string[] values1=new String[idtest1.count];

IDTest1.Values.CopyTo (values1,0);

MessageBox.Show (values1[0]+ "" +values1[1]);     Output HelloWorld

//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

namevaluecollectionnc= (NameValueCollection) configurationsettings.getconfig ("Test3");

MessageBox.Show (NC. Allkeys[0]. ToString () + "" +nc["Hello"]); Output HelloWorld

Configuration section Handlers

return type

SingleTagSectionHandler

Systems.Collections.IDictionary

DictionarySectionHandler

Systems.Collections.IDictionary

NameValueSectionHandler

Systems.Collections.Specialized.NameValueCollection

 

L sectiongroup: Custom configuration section Group

A configuration section group uses the <sectionGroup> element to divide similar configuration sections into the same group. The configuration section Group Declaration section creates a configuration section

Contains the elements, declares the configuration section group in the <configSections> element, and places the section belonging to the group in the <sectionGroup> element. Below

is an example of a configuration file that contains a configuration section group:

<?xml version= "1.0" encoding= "Utf-8"?>

<configuration>

     <configSections>

        < sectiongroup >

            <section 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:

namevaluecollectionnc= (NameValueCollection) configurationsettings.getconfig ("Testgroup/test");

MessageBox.Show (NC. Allkeys[0].   ToString () + "" +nc["Hello"]); //Output HelloWorld

2. Settings.settings configuration file Action

This use is not much, the operation is very simple, in this not detailed description.

 

II. User-defined file operations

1. XML configuration file Actions

XML configuration files are generally defined by our own format, because in some places we need to manipulate the XML for app.config without writing, and here we take it as an example to illustrate the operation of XML.

Privatevoid saveconfig (String connenctionstring)
{
XmlDocument doc=new XmlDocument ();
Get the full path to the configuration file
Stringstrfilename=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
Xmlattributeatt=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);
}

2. Registry Configuration Action

First, the registry is also stored as a key-value pair, and Dotnet provides operations on the registry.

Action Example:

         <span style= "FONT-SIZE:12PX;" >///<summary>///load information such as form position size from the registry///</summary> public static Voidloadformpositi On (System.Windows.Forms.Form Fo) {Microsoft.Win32.RegistryKey rk =microsoft.win32.registry.currentuse
            R.opensubkey ("Software\\\\mapwingisconfig", false); try {if (RK. GetValue (fo.name + "_x"). ToString ()!= "") && (RK. GetValue (fo.name + "_y"). ToString ()!= "") && (RK. GetValue (fo.name + "_w"). ToString ()!= "") && (RK. GetValue (fo.name+ "_h"). ToString ()!= "")) {fo.location = newSystem.Drawing.Point (int. Parse (RK. GetValue (fo.name + "_x"). ToString (), cultureinfo.invariantculture), Int. Parse (RK. GetValue (fo.name + "_y").

                    ToString (), CultureInfo.InvariantCulture)); Fo.size = newSystem.Drawing.Size (int. Parse (RK. GetValue (fo.name + "_w"). ToString (), cultureinfo.invariantculture), Int. Parse (RK. GetValue (fo.name + "_h").
                ToString (), CultureInfo.InvariantCulture)); } catch {} finally {RK.
            Close (); }///<summary>///saves the form location size information in the registry///</summary> public static Voi Dsaveformposition (System.Windows.Forms.Form Fo) {Microsoft.Win32.RegistryKey rk =microsoft.win32.regi Stry.

            Currentuser.createsubkey ("Software\\\\mapwingisconfig"); if (fo.visible &&fo.windowstate!= system.windows.forms.formwindowstate.minimized&&fo.location.x
                >-1 && fo.location.y >-1 && fo.size.width> 1 && Fo.Size.Height > 1) { Rk.
                SetValue (fo.name + "_x", fo.location.x); Rk.
                SetValue (fo.name + "_y", FO.LOCATION.Y); Rk.
                SetValue (fo.name + "_w", Fo.Size.Width); Rk.
        SetValue (fo.name + "_h", Fo.Size.Height);    } rk.
        Close (); }</span>

Third, application information configuration

Inherit the ApplicationSettingsBase class (C/S mode) by code and set the related properties in code.

1. Inheriting the class generally has class attributes [Settingsprovider ("System.Configuration.LocalFileSettingsProvider")]-details are as follows

2. Each property must be set to [Applicationscopedsetting ()] or [Usersocpedsetting ()], or you can set the default value [DefaultSettingValueAttribute ("100,100" )]

3. After the property setting is complete, instantiate the inherited class at the method level or within the method (as appropriate), and set the corresponding property when the form is loaded. There are two types of loader configuration methods-details are as follows.

4. If you need to be able to take advantage of event monitoring settings to change, save, load the actions

5. Save the settings when the form is unregistered.

Detailed

(i), LocalFileSettingsProvider---provide persistent storage for application settings classes.

1. This class provides a mechanism for the program to use the mechanism of configuring data to save the program's settings file to the default location.

2. The client does not show access to this class, but is automatically invoked by the setup mechanism when a service is required, such as: Many members in applicationsettingsbase use the class.

3. This class saves the configuration file as a. config XML file

1. If the property of the field is set to [Userscopedsetting ()], it is saved as a user.config file.

Save location C:\Documentsand settings\[Computer User name]\localsettings\application data\[assemblycompany ("Huzongzhe") an attribute in the Assembly]\

2. If the property of the field is set to [Applicationscopedsetting ()], it is saved as the program name].exe.config file.

Save location: In the same directory as the executable file.

4.toolstripmanager.loadsettings (this) and toolstripmanager.savesettings (this) method explain

First, Toolstripmanager provides operations for ToolStrip related types, including merging, splitting ToolStrip, rendering styles, and saving load settings.

Secondly, the location of LoadSettings and SaveSettings is C:\Documentsand settings\[computer username]\localsettings\application A property in the Assemblycompany ("Huzongzhe") Assembly]\

The file configuration provided with LocalFileSettingsProvider is the same location and is the same file.

Finally, the contents of the loadsettings: Size, IsDefault, Itemorder, Visible, Toolstrippanelname, Name, location, etc. 7 properties.

(b) The loader configuration method

1. Binding through function binding so that the data is bound directly to the configuration file when the program is loaded, and can be loaded directly into the XML when the value changes.

Binding Bndbackcolor = new Binding ("BackColor", FRMSETTINGS1,

"Formbackcolor", true,datasourceupdatemode.onpropertychanged);

This. Databindings.add (Bndbackcolor);

2. By means of extraction. This does not change dynamically after each modification and needs to be set manually.

This. Size = frmsettings1.formsize;

(iii), [Settingsgroupname ("System.Windows.Forms.ToolStripSettings.MapWinGIS.MainProgram.MapWinForm")] class properties

Sets the prefix name for each ToolStrip, which is the previously qualified name of each group

For example: The Tlbzoom toolbar is identified in the configuration file-->system.windows.forms.toolstripsettings.mapwingis.mainprogram.mapwinform.tlbzoom

(iv), method reload (); Reset (); Save (); Upgrade ();

The Reload () method reloads the value from the configuration file.

The Reset () method resets the setting to the default value.

The Save () method saves the currently set value.

Upgrade () The Update settings value.

 

code example:

 [Settingsprovider ("System.Configuration.LocalFileSettingsProvider")] [Settingsgroupname ("System.Windows.Forms.ToolStripSettings.MapWinGIS.MainProgram.MapWinForm")] Sealedclass toolstripsettings:applicationsettingsbase {public toolstripsettings (string settingskey): Base (Settingskey)/
        /It's ToolStrip's Name property {} [Userscopedsetting ()] public System.Drawing.Point Location {get {if (this["Location"] = = null) {if (th Is. Getpreviousversion ("Location") = = null) {return NewSystem.Drawing.Point (-1,-1
                   ); Return (System.Drawing.Point) (this.
               Getpreviousversion ("Location"));
            Return ((System.Drawing.Point) (this["Location"));
            } set {this["Location"] = value; } [UserscopedsettING (), Defaultsettingvalue ("Stripdocker.top")] public string Toolstrippanelname {get {if (string. IsNullOrEmpty ((String) (this["Toolstrippanelname"))) {//Set the value of the earlier setting I F (String. IsNullOrEmpty ((String) (this. Getpreviousversion ("Toolstrippanelname"))) {//default value Retu RN String.
                   Empty; Return (a String) (this.
               Getpreviousversion ("Toolstrippanelname"));
            Return ((String) (this["Toolstrippanelname"]);
            } set {this["toolstrippanelname"] = value;
        } [Userscopedsetting ()] [Defaultsettingvalue ("ImageAndText")] public string Displaystyle
               {get {const string defaultvalue = ' ImageAndText '; if (this["displaystyle"] = = null | | ((String) (this["Displaystyle"]) ==string. Empty) {//Set the early value if (this. Getpreviousversion ("displaystyle") = = NULL | | ((String) (this. Getpreviousversion ("Displaystyle")) = = String.
                   Empty) {///default value return defaultvalue; Return (a String) (this.
               Getpreviousversion ("Displaystyle"));
            Return ((String) (this["Displaystyle"]);
            } set {this["Displaystyle"] = value; }
        }
    }

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.