C # application configuration file App. config usage summary,

Source: Internet
Author: User
Tags allkeys connectionstrings

C # application configuration file App. config usage summary,

Add reference System. Configuration. dll, using System. Configuration;

The application configuration file is a standard XML file, and the XML tag and attribute are case sensitive.

Configuration is the root node. We often access the deleteworker, which is a set of configuration items in the. Net pre-defined configuration section under the <configuration> label.

<ConnectionStrings> node, used to configure database connection strings. You can use the <Add> node to Add multiple database connection strings. Shape:

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <configuration>
 3     <connectionStrings>
 4         <add name="conn" connectionString="this is connection string"/>
 5     </connectionStrings>
 6     <appSettings>
 7         <add key="key1" value="value1" />
 8         <add key="key2" value="value2" />
 9     </appSettings>
10 </configuration>
1 // ConfigurationManager.ConnectionStrings is a ConnectionStringSettingsCollection object
 2 // Get each connection string, each ConnectionStringSettings object has Name and ConnectionString properties
 3 for (int i = 0; i <ConfigurationManager.ConnectionStrings.Count; i ++)
 4 {
 5 string name = ConfigurationManager.ConnectionStrings [i] .Name;
 6 string connectionString = ConfigurationManager.ConnectionStrings [i] .ConnectionString;
 7 Console.WriteLine (i.ToString () + "." + Name + "=" + connectionString);
 8} // Each ConnectionStringSettings object has Name and ConnectionString properties
 9 foreach (ConnectionStringSettings conn in ConfigurationManager.ConnectionStrings)
10 {
11 string name = conn.Name;
12 string connectionString = conn.ConnectionString;
13 Console.WriteLine (name + "=" + connectionString);
14}
15
16 // AppSettings is a NameValueConnection type. Use AllKeys to return a string array of all the keys
17 string [] keys = ConfigurationManager.AppSettings.AllKeys;
18 for (int i = 0; i <keys.Length; i ++)
19 {
20 string key = keys [i];
21 // Index Value by Key
22 string value = ConfigurationManager.AppSettings [key];
23 Console.WriteLine (i.ToString () + "." + Key + "=" + value);
twenty four } 

Modify the configuration file:

Error Method:


1 private void AccessAppSettings ()
  2 {
  3 // Get the Configuration object
  4 Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.None);
  5 // Read the value of the <add> element according to the Key
  6 string name = config.AppSettings.Settings ["name"]. Value;
  7 // Write Value of <add> element
  8 config.AppSettings.Settings ["name"]. Value = "fx163";
  9 // Add <add> element
10 config.AppSettings.Settings.Add ("url", "http://www.fx163.net");
11 // Remove the <add> element
12 config.AppSettings.Settings.Remove ("name");
13 // Must remember to save, you can also write config.Save () without parameters
14 config.Save (ConfigurationSaveMode.Modified);
15 // Refresh, otherwise the program reads the previous value (may be loaded into memory)
16 System.Configuration.ConfigurationManager.RefreshSection ("appSettings");
17}


The value of the program has been modified. However, when you open app. config to view it, the value is still not changed. If the program is restarted, the old value is used. This method can only read values. Values cannot be written or modified.

The correct method is to modify the configuration file according to the common xml file. Otherwise, the common problem is that what you modified was not written to the file at last!

Generally, the configuration file is in the same directory as the executable exe file, and only one is added after the name. therefore, you can use Application. executeablePath + ". cofig, but AppDomain is more recommended. currentDomain. setupInformation. the ConfigurationFile statement is used to directly obtain the location of the configuration file of the current program. The specific reason is described later.

1 using System.Xml;
 2 // The first parameter is the value of the add node in the xml file, and the second parameter is the key of the add node
 3 private void SaveConfig (string ConnenctionString, string strKey)
 4 {
 5 XmlDocument doc = new XmlDocument ();
 6 // Get the full path of the configuration file
 7 string strFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
 8 // string strFileName = AppDomain.CurrentDomain.BaseDirectory + "\\ exe.config";
 9 doc.Load (strFileName);
10 // Find all elements named "add"
11 XmlNodeList nodes = doc.GetElementsByTagName ("add");
12 for (int i = 0; i <nodes.Count; i ++)
13 {
14 // Get the key attribute of the current element
15 XmlAttribute att = nodes [i] .Attributes ["key"];
16 // Determine if the current element is the target element based on the first attribute of the element
17 if (att.Value == strKey)
18 {
19 // Assign a value to the second attribute in the target element
20 att = nodes [i] .Attributes ["value"];
21 att.Value = ConnenctionString;
22 break;
twenty three                 }  
twenty four             }  
25 // Save the changes above
26 doc.Save (strFileName);
27 System.Configuration.ConfigurationManager.RefreshSection ("appSettings");
28} 

Now let's look back at the above function and look at its last line. What is its function?

Find the msdn document and find that Microsoft has configured the configuration file App for performance considerations. config uses a cache policy. Therefore, although the above function does modify the node value in the disk file, when the previous function is used for reading, it will still get the original value, as if it was not modified! Therefore, you must use this sentence to refresh the file once, and force the program to read the file from the disk next time!

Now, when using Visual Studio to write C # program, all the children's shoes should have encountered a pain point, that is, when debugging, the configuration file is clearly modified in the program, however, when the program is re-executed next time, it is found that the program has not changed at all. Open the config file corresponding to the exe file and check that the file has not changed !!!! Obviously, it is operated as an xml file. How can this happen ?!

When you open the config file, you will find that the value of the xml file has changed! Pair ~ VS in both Debug and Release, the running program is the program with vshost, And the configuration corresponding to the program is modified. The content in the config corresponding to the restart, which is why the original state is restored after each re-opening of the program.

When the program is debugged in VS, the program running is different from the program running directly in the bin folder. Therefore, we recommend that you use AppDomain. currentDomain. setupInformation. configurationFile to obtain the configuration file of the current running program.

Of course, do not worry about this difference. After the program is debugged, the program is generally started manually from the folder. At this time, there will be no such problems. Everything will be back to normal!

 

Reference: https://blog.csdn.net/xiangxianghehe/article/details/77825868

Https://blog.csdn.net/celte/article/details/9749389


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.