C # Read and write app.config,configurationmanager.appsettings failed solution

Source: Internet
Author: User
Tags allkeys change settings connectionstrings
You may know that Properties.Settings can be used to perform similar tasks in WinForm applications, but these actually use the App.config configuration file.

This article explores how to access App.config in code. The use of App.config is far more complicated than the above mentioned uses, so only the most basic appSettings configuration section is discussed.

First. Overview of configuration files:

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 configuration section predefined by .Net. The structure of the configuration file we often use is the following form. I have an impression first, and I will have a clearer understanding through the following examples. The following "configuration section" can be understood as a node for configuring an XML.

Common configuration file modes:

    <configuration>
    <configSections> // Configuration section declaration area, including configuration section and namespace declaration
    <section> // Configuration section declaration
    <sectionGroup> // Define the configuration section group
    <section> // Configuration section declaration in configuration section group
    <appSettings> // Predefined configuration section
    <Custom element for configuration section> // Configuration section setting area

Here is an example of the most common application configuration file, with only the appSettings section:

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

In the predefined appSettings section (note the case), there are a lot of elements, these element names are "add", and there are two attributes are "key" and "value".

.NET provides access to the appSettings section. In .NET 1.0 and 1.1, you can use System.Configuration.ConfigurationSettings.AppSettings ["Key"] to access the value attribute of the <add> element with key = "Key".

Note: Now .Net FrameWork 2.0 has clearly stated that this ConfigurationSettings property is deprecated, it is recommended to change to ConfigurationManager or WebConfigurationManager.

To use System.Configuration.ConfigurationManager, you need to add a reference to the system.configuration.dll assembly in the project. (Right-click the project name in the Solution Manager, select Add Reference from the right-click menu, and you can find it under the .NET tab.)

After adding the reference, you can use ConfigurationManager.AppSettings ["Key"] to read the corresponding value.

However, the ConfigurationManager.AppSettings property is read-only and does not support modifying property values. This is because it is said that Microsoft does not recommend that we write the app.config file dynamically. Instead, it is recommended that after manual configuration, only static access is performed when the program is running.

If you really need to modify in the program, that is, write to App.Config, please read on.

 
Read and write operations in the appSettings configuration section

The method of reading the AppSettings section of the App.config file is relatively simple and can be accessed through the method of System.Configuration.ConfigurationManager.AppSettings ["Key"] above, but as already mentioned earlier, this method does not provide writing.

If you want to write a configuration file, you can use the ConfigurationManager object to perform the operation of opening the configuration file. After that, a Configuration object will be returned, and you can use this object to perform operations (you can add, delete, change and check).

The implementation code is given below (add reference to using System.Configuration namespace)

private void AccessAppSettings ()
{
// Get the Configuration object
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.None);
// Read the value of the <add> element according to the Key
string name = config.AppSettings.Settings ["name"]. Value;
// Write Value of <add> element
config.AppSettings.Settings ["name"]. Value = "xieyc";
// Add <add> element
config.AppSettings.Settings.Add ("url", "http://www.xieyc.com");
// Remove the <add> element
config.AppSettings.Settings.Remove ("name");
// Must remember to save, you can also write config.Save () without parameters
config.Save (ConfigurationSaveMode.Modified);
// Refresh, otherwise the program reads the previous value (may be loaded into memory)
System.Configuration.ConfigurationManager.RefreshSection ("appSettings");
}

have to be aware of is:

1. Accessing the <add> element according to the non-existent Key value, and even removing the non-existing element using the remove () method will not cause an exception, the former will return null.
2. Adding an existing <add> element will not cause an exception, but instead concat the existing Value and the new Value, separated by ",", for example: "olldvalue, newvalue"
3. After the project is compiled, under the bin \ Debuge file in the run directory, two configuration files will appear, one named "ProjectName.EXE.config" and the other named "ProjectName.vshost.exe.config". The first file is the configuration file actually used by the project. Changes made during the program run will be saved here; the second file is actually a synchronization file of "App.config" in the original code. Will change.
4. Pay special attention to case (XML files are case sensitive), such as the appSettings configuration section.
5. Some readers may think that since app.config is standard XML, of course, it can also be read and written by manipulating general XML files. This is certainly possible! For details, please refer to the codes in references [2] and [3] at the end of the article, but I think that this loses the meaning of VS providing the app.config file, it is not as convenient as defining a configuration file yourself.

 

This article only roughly describes the access method of the appSettings configuration section in the app.config file. The operation of the connectionStrings configuration section is basically similar. You can also customize the configuration section. These advanced usages can be experienced by yourself. The management of the configuration file app.config by VS is still very powerful. For example, the Settings settings of the WinForm application (accessible in the IDE or through code) actually use the app.config file.


C # read and write data in app.config detailed examples tutorial



Read statement:
          String str = ConfigurationManager.AppSettings ["DemoKey"];

Write the statement:

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

Configuration file content format: (app.config)

<? xml version = "1.0" encoding = "utf-8"?>
<configuration>
<appSettings>
    <add key = "DemoKey" value = "*" />
</ appSettings>
</ configuration>

System.Configuration.ConfigurationSettings.AppSettings ["Key"];
But now FrameWork2.0 has clearly stated that this property is obsolete. And it is recommended to change to ConfigurationManager or WebConfigurationManager. And the AppSettings property is read-only and does not support modifying property values.

But to call the ConfigurationManager, you must first add a reference to the system.configuration.dll assembly in the project. (Right-click the project name in the Solution Manager and select Add Reference from the context menu. You can find it under .net TablePage) After adding the reference, you can use String str = ConfigurationManager.AppSettings ["Key"] to get the corresponding value .

Update the 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 configuration file was updated successfully.


Second,Read and write configuration file app.config
The configuration file is provided in .Net, so that we can deal with the configuration information in a lot, this configuration is in XML format. And .Net has provided some functions to access this file.

1. Read 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 a method to directly access the <appsettings> (note the case) element. There are many child elements in this element. These child element names are "add" and there are two attributes: "key" and " value ". Generally, we can write our own configuration information in this area and access it in the following ways:

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

Behind appsettings is the value of the key attribute of the child element, such as appsettings ["connenctionstring"], we are accessing the <add key = "ConnenctionString" value = "*" /> child element, and its return value is "*" , Which is the value of the value attribute.

2. Set configuration information

If the configuration information is static, we can configure it manually, paying attention to the format. If the configuration information is dynamic, we need to write a program to implement it. There is no function to write the configuration file in .Net, we can use the way of manipulating the XML file to operate the configuration file. The following is an example of writing a configuration file.
     

 private void SaveConfig (string ConnenctionString)
         {
             XmlDocument doc = new XmlDocument ();
             // Get the full path of 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 ++)
             {
                 // Get the key attribute of the current element
                 XmlAttribute att = nodes [i] .Attributes ["key"];
                 // Determine if the current element is the target element based on the element's first attribute
                 if (att.Value == "ConnectionString")
                 {
                     // Assign a value to the second attribute in the target element
                     att = nodes [i] .Attributes ["value"];
                     att.Value = ConnenctionString;
                     break;
                 }
             }
             // Save the changes above
             doc.Save (strFileName);
         }


Read and write configuration files in VS2005

In VS2003, only the reading function is provided for the application configuration file (app.config or web.config). In VS2005, the function of the configuration file has been greatly enhanced. In VS2005, two classes, Configuration and ConfigurationManager, are generally used for reading and writing application configuration files. The ConfigurationManager class provides an accessible function for client applications. After using the ConfigurationManager object to open the configuration file, a Configuration object will be 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. This 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 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 format of the generated configuration file 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. Configuration file 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 structure of the configuration file we often use is like the following. I have an impression first, and I will have a clearer understanding through the following examples. The following "configuration section" can be understood as a node for configuring an XML.

Common configuration file modes:

<configuration>
         <configSections> // Configuration section declaration area, including configuration section and namespace declaration
                 <section> // Configuration section declaration
             <sectionGroup> // Define the configuration section group
                 <section> // Configuration section declaration in configuration section group
         <appSettings> // Predefined configuration section
<Custom element for configuration section> // Configuration section setting area

2. Only the configuration file and access method of the appSettings section

Below is an example of the most common application configuration file, only the appSettings section.


<? 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 see how such a configuration file works.

string _connectionString = ConfigurationSettings.AppSettings ["connectionstring"];

Use the static property AppSettings of the ConfigurationSettings class to directly configure the configuration information in the configuration file. The type of this property is NameValueCollection.

3. Custom configuration file

3.1 Custom Configuration Section

A user-defined configuration section is divided into two parts in the configuration file: the first is to declare the configuration section in the <configSections> </ configSections> configuration section ("<section>" in the configuration file mode above), and <configSections> </ configSections> Set the configuration section afterwards ("<Custom element for configuration section>" in the configuration file mode above), which is similar to a variable that is declared first and then used the same. The statement to declare a configuration file is as follows:
<section "type =" "/>
<section>: declare a new configuration section to create a new configuration section.

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

Different types not only set the configuration section in different ways, but also have differences in the operation of accessing the configuration file. Below we will give a configuration file

Example, let it contain these three different types.


<? 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 explain the custom configuration section above. In the declaration section, use <section type = "System.Configuration.SingleTagSectionHandler" /> to declare a configuration section whose name is Test1 and whose type is SingleTagSectionHandler. In the setting configuration section, use <Test1 setting1 = "Hello" setting2 = "World" /> to set a configuration section. The first setting value is Hello and the second value is World. Of course, there can be more . The other two configuration sections are similar to this.
Let's see how to access these custom configuration sections in the program. We used the static method GetConfig of the ConfigurationSettings class to get the information of the custom configuration section.

public static object GetConfig (string sectionName);

Here is the code to access these three configuration sections:


// Access the configuration section Test1
IDictionary IDTest1 = (IDictionary) ConfigurationSettings.GetConfig ("Test1");
string str = (string) IDTest1 ["setting1"] + "" + (string) IDTest1 ["setting2"];
MessageBox.Show (str); // Output Hello World

// Method 2 for accessing the configuration section Test1
string [] values1 = new string [IDTest1.Count];
IDTest1.Values.CopyTo (values1,0);
MessageBox.Show (values1 [0] + "" + values1 [1]); // Output Hello World

// Access the 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 the configuration section Test3
NameValueCollection nc = (NameValueCollection) ConfigurationSettings.GetConfig ("Test3");
MessageBox.Show (nc.AllKeys [0] .ToString () + "" + nc ["Hello"]); // Output Hello World
Through the above code, we can see that different types return different types through GetConfig, and the specific methods for obtaining configuration content are also different.

Configuration section handler
Return type

SingleTagSectionHandler
Systems.Collections.IDictionary

DictionarySectionHandler
Systems.Collections.IDictionary

NameValueSectionHandler
Systems.Collections.Specialized.NameValueCollection


3.2 Custom Configuration Section Group
Configuration section groups use the <sectionGroup> element to group similar configuration sections into the same group. The configuration section group declaration section creates an include element for the configuration section, declares the configuration section group in the <configSections> element, and places the sections belonging to the group in the <sectionGroup> element. The following is an example of a configuration file containing configuration section groups:

<? 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:
NameValueCollection nc = (NameValueCollection) ConfigurationSettings.GetConfig ("TestGroup / Test");
MessageBox.Show (nc.AllKeys [0] .ToString () + "" + nc ["Hello"]); // Output Hello World


Configure App.config


1. Add the app.config file to the project:

Right-click the project name and select "Add" → "Add New Item". In the "Add New Item" dialog box that appears, select "Add Application Configuration File"; if the project has no previous configuration file, the default file name is App.config, click OK. The app.config file that appears in the designer view is:

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

After the project is compiled, under the bin \ Debuge file, there will be two configuration files (taking 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 actually used by the project, and changes made during the program run will be saved here; the second file is the synchronization file of the original code "app.config", which will not occur during the program run change.

2. connectionStrings configuration section:

Please note: If your SQL version is 2005 Express, the default SQL server instance name during installation is localhost \ SQLExpress. You must change the "Data Source = localhost;" sentence in the following example to "Data Source = localhost \ SQLExpress;" Do not add spaces around the equal 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 it is the configuration of the current user, please use the userSettings configuration section, the format is the same as the following configuration writing requirements.

<!-Parameters required for initializing the inventory 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

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

4.1 Reading the connectionStrings configuration section

/// <summary>
/// Return the data connection string according to 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 the 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; // Record if the connection string already exists
    // If the connection string to be changed 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);
    }
    // Add the new connection string to the configuration file.
    config.ConnectionStrings.ConnectionStrings.Add (mySettings);
    // Save changes to the configuration file
    config.Save (ConfigurationSaveMode.Modified);
    // Force reload the ConnectionStrings configuration section of the configuration file
    ConfigurationManager.RefreshSection ("ConnectionStrings");
}

4.3 Read the appStrings configuration section

/// <summary>
/// Return value item of appSettings configuration section in * .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 the connectionStrings configuration section

/// <summary>
/// Add a key and value pair in 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 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");
}

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.