C # configuration File App. Config Usage summary-go

Source: Internet
Author: User

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

First, the format of the App. config configuration file that I use is as follows:

[HTML]View Plaincopyprint?
  1. <? XML version= "1.0" encoding="Utf-8" ?>
  2. <configuration>
  3. <appSettings>
  4. <add key= "serverip" value="127.0.0.1"></Add>
  5. <add key="DataBase" value="Warehousedb"></Add>
  6. <add key="user" value="sa"></Add>
  7. <add key= "password" value="sa"></Add>
  8. </appSettings>
  9. </configuration>
<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <appSettings>        <add key= " ServerIP "value=" 127.0.0.1 "></add>        <add key=" DataBase "value=" Warehousedb "></add>    <add key= "user" value= "sa" ></add>    <add key= "password" value= "sa" ></add>  </ Appsettings></configuration>

Therefore, the configuration file reads as follows: (still a simple example of the above file)

[CSharp]View Plaincopyprint?
    1. static string str  =  "data source="  +  System.configuration.configurationmanager.appsettings[ "ServerIP"] +  "initial catalog ="  +  System.configuration.configurationmanager.appsettings[ "DataBase"] +  "user"] +  " password="  +  System.configuration.configurationmanager.appsettings[ "password"] ;  
static string str = "Data source=" + system.configuration.configurationmanager.appsettings["ServerIP"] + "; Initial Catalog = "+ system.configuration.configurationmanager.appsettings[" DataBase "] +"; User id= "+ system.configuration.configurationmanager.appsettings[" user "] +"; password= "+ system.configuration.configurationmanager.appsettings[" Password "];

In this way, the required information is read out from the configuration file, forming a set of strings to connect to the database.

For modifying the configuration file,

Many articles describe modifying the values in app. config with the following methods:

[CSharp]View Plaincopyprint?
    1. Configuration config = configurationmanager.openexeconfiguration (configurationuserlevel.none);
    2. Config. appsettings.settings["Db_uid"].  Value = "Demo";
    3. Config. Save (Configurationsavemode.full);
Configuration config = configurationmanager.openexeconfiguration (configurationuserlevel.none); config. appsettings.settings["Db_uid"]. Value = "Demo"; config. Save (Configurationsavemode.full);

It turns out that this practice is not feasible. Although the value of the program runtime has been modified. However, if you open the App. Config view, you will see that the values are still unchanged. If you restart the program, the previous old values will be used. Only values can be read in this way. The value cannot be written or modified.

Note that the correct approach is to change the configuration file according to the normal XML file, otherwise, often the problem is that you have modified the thing actually didn't write to the file at all! Finally, the modification failed!

As a normal XML file read, you first need to know how to find the path of the file. We know that the general configuration file is in the same directory as the executable EXE file, and only after the name is added. config Therefore, it can be obtained by means of application.executeablepath+ ". Cofig". However, it is more recommended to use AppDomain.CurrentDomain.SetupInformation.ConfigurationFile to directly obtain the location of the current program's configuration file, for specific reasons, and then described.

Here are some of the operations functions I use.

[CSharp]View Plaincopyprint?
  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 with the name "add"
  11. XmlNodeList nodes = doc.  getElementsByTagName ("add");
  12. For (int i = 0; i < nodes. Count; i++)
  13. {
  14. //Gets the key property of the current element
  15. XmlAttribute att = nodes[i].  attributes["Key"];
  16. //Based on the first attribute of the element to determine whether the current element is a target 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 ;
  23. }
  24. }
  25. //Save the above changes
  26. Doc. Save (strFileName);
  27. System.Configuration.ConfigurationManager.RefreshSection ("appSettings");
  28. }
Using system.xml;//The first parameter is the value of the Add node in the Xml file, the second parameter is the keyprivate void saveconfig of the Add node (string connenctionstring, String            strkey) {XmlDocument doc = new XmlDocument ();            Gets the full path of the configuration file string strFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;            String strfilename= AppDomain.CurrentDomain.BaseDirectory + "\\exe.config"; Doc.            Load (strFileName); Find all the elements with the name "add" xmlnodelist nodes = Doc.            getElementsByTagName ("add"); for (int i = 0; i < nodes. Count; i++) {//Gets the key attribute of the current element XmlAttribute att = nodes[i].                attributes["Key"]; Determines whether the current element is the target element if (ATT) based on the first attribute of the element. Value = = strkey) {//assigns to the second attribute in the target element att = nodes[i].                    attributes["value"]; Att.                    Value = connenctionstring;                Break }}//Save the above modification doc. Save (strFileName); System.Configuration.ConfigurationManager.RefreshSection ("AppSettings");}

Now go back or look at the function above, look at its last line, what is its function?

Finding the MSDN documentation reveals that Microsoft has a cache policy for Profile App. Config for performance reasons, so Although the above function does modify the value of the node in the disk file, it will still get the original value when it is read with the previous function. As if not modified! So, you have to use this sentence, to do a refresh, forcing the next time the program reads, read from the disk file!

OK, now use Visual Studio to write C # program Children's shoes should have encountered an egg pain problem, is in the debug, obviously in the program to modify the configuration file, but the next time you re-execute the program, found that the program has not changed, Open the config file corresponding to the EXE file view, found that the file does not change!!!! Clearly is as an XML file to operate, how can this?!

In fact, this involves the operating mechanism of VS, the careful children's shoes will be in the EXE file in the same directory, found that there is a corresponding vshost.exe, as well as the Vshost.exe.config file, when you open this config file here will find that The value of the XML file in this area has changed! On the drip ~vs, whether in debug or release, running program is this with Vshost program, modify the program is also the corresponding CONFIG. At that time, when the program just started, but it is read the original and EXE file corresponding config file, the config file content to replace the original and Vshost.exe corresponding config inside the content, which is why each time after the resumption of the program after the reason for the original.

Since the program in the debug in VS, run the program and go directly to the Bin folder to run the program is not the same, so it is more recommended to use AppDomain.CurrentDomain.SetupInformation.ConfigurationFile to get the configuration file for the currently running program.

Of course, this difference do not worry, and so the program after debugging, after, the program is generally from the folder manually started, this time, there is not so many problems above. Everything will be back to normal!

C # configuration File App. Config Usage summary-go

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.