How to read and modify app.config files in a C # project

Source: Internet
Author: User

This article briefly describes the method for reading and modifying app.config files in a C # project, AppConfig The most important feature is that it unifies command-line options and configuration file options into one data structure.

1. Add the app.config file to the project in the C # project instance:

Right-click the project name in the C # project instance. 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 previously have a profile, the default file name is "app.config" and click OK. The app.config file that appears in the designer view is:

<?xmlversionxmlversionxmlversionxmlversion= "1.0" encoding= "Utf-8"?>     
<configuration>     
</ Configuration>

After the project has been compiled, under the Bindebuge file, there will be two profiles (take this project as an example) and one named "* * *." 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.

2. SQL expressconnectionstrings Configuration:

Note: Do not add the above space on either side of the equals number.

<connectionStrings>     
         <addnameaddname= "***name"  
              connectionstring= "Data source=localhost;initial Catalog=jxcbook; User id=sa;password=******** "  
              providername=" System.Data.SqlClient  />     
</connectionStrings>

3. appsettings/usersetting 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.

<appSettings>     
         <clear  />     
         <addkeyaddkeyaddkeyaddkey= "userName" value= ""  />     
         <addkeyaddkeyaddkeyaddkey= "password" value= ""  />     
</appSettings>

4. Read and update app.config

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

(1) Read connectionstrings configuration section

<summary>     
///Returns the data connection string      
///</summary>///<param name= According to the connection string name ConnectionName     
ConnectionName "></param>     
///<returns></returns>     
private static string Getconnectionstringsconfig (String connectionname)      
{      
        string connectionString =       
        Configurationmanager.connectionstrings[connectionname]. Connectionstring.tostring ();      
           
        return connectionString;      
}

(2) Update connectionstrings configuration section

<summary>///Update connection string///</summary>///<param name= "NewName" > Connection string name </param> <param name= "newconstring" > Connection string content </param>///See more highlights in this column: http://www.bianceng.cnhttp:// www.bianceng.cn/Programming/csharp////<param name= "Newprovidername" > 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 that you want to change already exists if (Configurationmanager.connectionstrings[newname]!= null)      
    {ismodified = true; //Create a new connection string instance connectionstringsettings mysettings = new Connectionstringsettings (newn      
    Ame, newconstring, newprovidername); Open the executable configuration file *.exe.config Configuration config = configurationmanager.openexeconfiguration (config      
    Urationuserlevel.none); //If the connection string already exists, first delete it if (ismodified) {config.      
    ConnectionStrings.ConnectionStrings.Remove (NewName);      
    //Add a new connection string to the configuration file. Config.      
    CONNECTIONSTRINGS.CONNECTIONSTRINGS.ADD (mysettings); Saves the change config to the configuration file.      
    Save (configurationsavemode.modified);      
Forces the connectionstrings configuration section of the configuration file to reload Configurationmanager.refreshsection ("connectionstrings"); }

(3) Read Appstrings configuration section

<summary>     
///Returns the value entry for the appsettings configuration section in the ***.exe.config file      
///</summary>     
///<param Name= "Strkey" ></param>     
///<returns></returns>     
private static string Getappconfig ( String strkey)      
{      
    foreach (string key in Configurationmanager.appsettings)      
    {      
        if (key = = strkey)      
        { C11/>return Configurationmanager.appsettings[strkey];      
        }      
    return null;      
}

(4) Update connectionstrings configuration section

<summary>///Add a pair of keys, value pairs///</summary>///<param name= "n" in the ***.exe.config file appsettings configuration section Ewkey "></param>///<param name=" newvalue "></param> private static void Updateappconfig (ST          
    Ring NewKey, string newvalue) {bool ismodified = false;          
            foreach (string key in Configurationmanager.appsettings) {if (Key==newkey) {      
        IsModified = true; }//Open app.config of executable Configuration Config = Configur      
    Ationmanager.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"); }

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/csharp/

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.