Use of configuration files in C #

Source: Internet
Author: User
Tags connectionstrings

1. Add the app. config file to the project:
Right-click the project name and select "add"> "Add new project". In the displayed "Add new project" dialog box, select "add application ".ProgramConfiguration file. If there is no configuration file in the project before, the default file name is "app. config" and click "OK ". The app. config file that appears in the designer view is:

View plaincopy to clipboardprint?
    1. <? Xmlversion ="1.0"Encoding ="UTF-8"?>
    2. <Configuration>
    3. </Configuration>

<? Xmlversion = "1.0" encoding = "UTF-8"?> <Br/> <configuration> <br/> </configuration> <br/>
After the project is compiled, Run "bin \ users. config ". The first file is the configuration file actually used by the project. All changes made during the program running will be saved here. The second file is the originalCodeThe synchronization file of "app. config" will not be changed during the program running.
2. connectionstrings configuration section:
NOTE: If your SQL version is 2005 Express, the name of the SQL server instance is localhost \ sqlexpress by default. You must change "Data Source = localhost; "is" Data Source = localhost \ sqlexpress; ". Do not add spaces on both sides of the equal sign.

View plaincopy to clipboardprint?
  1. <! -- Database connection string -->
  2. <Connectionstrings>
  3. <Clear/>
  4. <Addname ="Conjxcbook"
  5. Connectionstring ="Data Source = localhost; initial catalog = jxcbook; user id = sa; Password = ********"
  6. Providername ="System. Data. sqlclient"/>
  7. </Connectionstrings>

<! -- Database connection string --> <br/> <connectionstrings> <br/> <clear/> <br/> <addname = "conjxcbook" <br/> connectionstring = "Data Source = localhost; initial catalog = jxcbook; user id = sa; Password = ********* "<br/> providername =" system. data. sqlclient "/> <br/> </connectionstrings> <br/>
3. appsettings configuration section:
The appsettings configuration section is the configuration of the entire program. If you configure the current user, use the usersettings configuration section. The format is the same as the following configuration writing requirements.

View plaincopy to clipboardprint?
  1. <! -- Parameters required for invoicing management system initialization -->
  2. <Deleetask>
  3. <Clear/>
  4. <Add key ="Username"Value =""/>
  5. <Add key ="Password"Value =""/>
  6. <Add key ="Department"Value =""/>
  7. <Add key ="Returnvalue"Value =""/>
  8. <Add key ="Pwdpattern"Value =""/>
  9. <Add key ="Userpattern"Value =""/>
  10. </Appsettings>

<! -- Parameters required for the initialization of the invoicing Management System --> <br/> <appsettings> <br/> <clear/> <br/> <addkey = "username" value = ""/> <br/> <addkey = "password" value = ""/> <br/> <addkey = "department" value = ""/> <br/> <addkey = "returnvalue" value = ""/> <br/> <addkey = "pwdpattern" value = ""/> <br/> <addkey = "userpattern" value = ""/> <br/> </appsettings> <br/>
4. Read and Update app. config
For the read and write operations on the app. config file, refer to the networkArticle: Http://www.codeproject.com/csharp/ systemconfiguration. asp is titled "read/write app. config file with. NET 2.0.
Note: To use the following code to access the app. config file, in addition to adding a reference to system. configuration, you must also add a reference to system. configuration. dll in the project.
4.1 read connectionstrings configuration section

View plaincopy to clipboardprint?
  1. /// <Summary>
  2. /// Connectionname returns the data connection string based on the connection string name
  3. /// </Summary>
  4. /// <Param name = "connectionname"> </param>
  5. /// <Returns> </returns>
  6. Private Static StringGetconnectionstringsconfig (StringConnectionname)
  7. {
  8. StringConnectionstring =
  9. Configurationmanager. connectionstrings [connectionname]. connectionstring. tostring ();
  10. Console. writeline (connectionstring );
  11. ReturnConnectionstring;
  12. }

/// <Summary> <br/> // return the data connection string based on the connectionname of the connection string <br/> /// </Summary> <br/> /// <Param name = "connectionname"> </param> <br/> // <returns> </returns> <br/> Private Static string getconnectionstringsconfig (string connectionname) <br/>{< br/> string connectionstring = <br/> configurationmanager. connectionstrings [connectionname]. connectionstring. tostring (); <br/> console. writeline (connectionstring); <br/> return connectionstring; <br/>}< br/>
4.2 connectionstrings configuration update

View plaincopy to clipboardprint?
  1. /// <Summary>
  2. /// Update the connection string
  3. /// </Summary>
  4. /// <Param name = "newname"> connection string name </param>
  5. /// <Param name = "newconstring"> connection string content </param>
  6. /// <Param name = "newprovidername"> data provider name </param>
  7. Private Static VoidUpdateconnectionstringsconfig (StringNewname,
  8. StringNewconstring,
  9. StringNewprovidername)
  10. {
  11. BoolIsmodified =False;// Record whether the connection string already exists
  12. // If the connection string to be modified already exists
  13. If(Configurationmanager. connectionstrings [newname]! =Null)
  14. {
  15. Ismodified =True;
  16. }
  17. // Create a connection string instance
  18. Connectionstringsettings mysettings =
  19. NewConnectionstringsettings (newname, newconstring, newprovidername );
  20. // Open the executable configuration file *. EXE. config
  21. Configuration Config =
  22. Configurationmanager. openexeconfiguration (configurationuserlevel. None );
  23. // If the connection string already exists, delete it first
  24. If(Ismodified)
  25. {
  26. Config. connectionstrings. connectionstrings. Remove (newname );
  27. }
  28. // Add a new connection string to the configuration file.
  29. Config. connectionstrings. connectionstrings. Add (mysettings );
  30. // Save the changes made to the configuration file
  31. Config. Save (configurationsavemode. modified );
  32. // Force re-load the connectionstrings configuration section of the configuration file
  33. Configurationmanager. refreshsection ("Connectionstrings");
  34. }

/// <Summary> <br/> // update the connection string <br/> /// </Summary> <br/> /// <Param name = "newname "> connection string name </param> <br/> // <Param name =" newconstring "> connection string content </param> <br/> // <Param name = "newprovidername"> data provider name </param> <br/> Private Static void updateconnectionstringsconfig (string newname, <br/> string newconstring, <br/> string newprovidername) <br/>{< br/> bool ismodified = false; // record whether the connection string already exists <br/> // if the connection string to be modified has been saved In <br/> If (configurationmanager. connectionstrings [newname]! = NULL) <br/>{< br/> ismodified = true; <br/>}< br/> // create a connection string instance <br/> connectionstringsettings mysettings = <br/> New connectionstringsettings (newname, newconstring, newprovidername ); <br/> // open the executable configuration file *. EXE. config <br/> Configuration Config = <br/> configurationmanager. openexeconfiguration (configurationuserlevel. none); <br/> // if the connection string already exists, delete it first <br/> If (ismodified) <br/>{< br/> config. connectionstrings. connectionstrings. remove (newname); <br/>}< br/> // Add a new connection string to the configuration file. <br/> config. connectionstrings. connectionstrings. add (mysettings); <br/> // Save the changes made to the configuration file <br/> config. save (configurationsavemode. modified); <br/> // force the connectionstrings configuration section of the configuration file to be reloaded <br/> configurationmanager. refreshsection ("connectionstrings"); <br/>}< br/>
4.3 read the appstrings configuration section

View plaincopy to clipboardprint?
  1. /// <Summary>
  2. /// Return the value item in the configuration section of the ettings in *. EXE. config file.
  3. /// </Summary>
  4. /// <Param name = "strkey"> </param>
  5. /// <Returns> </returns>
  6. Private Static StringGetappconfig (StringStrkey)
  7. {
  8. Foreach(StringKeyInConfigurationmanager. configurettings)
  9. {
  10. If(Key = strkey)
  11. {
  12. ReturnConfigurationmanager. configurettings [strkey];
  13. }
  14. }
  15. Return Null;
  16. }

/// <Summary> <br/> // return *. EXE. <br/> // </Summary> <br/> // <Param name = "strkey"> </param> <br/> // <returns> </returns> <br/> Private Static string getappconfig (string strkey) <br/>{< br/> foreach (string key in configurationmanager. appsettings) <br/>{< br/> If (Key = strkey) <br/>{< br/> return configurationmanager. appsettings [strkey]; <br/>}< br/> return NULL; <br/>}< br/>
4.4 connectionstrings configuration update

View plaincopy to clipboardprint?
  1. /// <Summary>
  2. /// In the *. EXE. config file, add a pair of key and value pairs to the deleettings configuration section.
  3. /// </Summary>
  4. /// <Param name = "newkey"> </param>
  5. /// <Param name = "newvalue"> </param>
  6. Private Static VoidUpdateappconfig (StringNewkey,StringNewvalue)
  7. {
  8. BoolIsmodified =False;
  9. Foreach(StringKeyInConfigurationmanager. configurettings)
  10. {
  11. If(Key = newkey)
  12. {
  13. Ismodified =True;
  14. }
  15. }
  16. // Open app. config of executable
  17. Configuration Config =
  18. Configurationmanager. openexeconfiguration (configurationuserlevel. None );
  19. // You need to remove the old settings object before you can replace it
  20. If(Ismodified)
  21. {
  22. Config. Fig. settings. Remove (newkey );
  23. }
  24. // Add an application setting.
  25. Config. appsettings. settings. Add (newkey, newvalue );
  26. // Save the changes in APP. config file.
  27. Config. Save (configurationsavemode. modified );
  28. // Force a reload of a changed section.
  29. Configurationmanager. refreshsection ("Appsettings");
  30. }
  31. Zookeeper ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    Multi-layer configsections

    Source Address

    Http://gb2013.blog.163.com/blog/static/21735301201021253713453/

    <? XML version = "1.0" encoding = "UTF-8"?>
    <Configuration>
    <Configsections>
    <Section name = "student" type = "system. configuration. dictionarysectionhandler"/>
    </Configsections>
    <Student>
    <Add key = "name" value = "http://www.cnblogs.com/i80386/archive/2011/10/27/amily"/>
    <Add key = "Age" value = "http://www.cnblogs.com/i80386/archive/2011/10/27/15"/>
    <Add key = "sex" value = "http://www.cnblogs.com/i80386/archive/2011/10/27/female"/>
    </Student>
    </Configuration>

    Note: configsections is equivalent to defining variables and must be placed in configuration

    Idictionary istudent = (idictionary) configurationmanager. getsection ("student ");
    String [] keys = new string [istudent. Keys. Count];
    String [] values = new string [istudent. Keys. Count];

    Istudent. Keys. copyto (keys, 0 );
    Istudent. Values. copyto (values, 0 );

    foreach (var key in keys)
    {< br> console. writeline (key);
    }< br> foreach (VaR value in values)
    {< br> console. writeline (value);
    }

    foreach (var key in istudent. keys)
    {< br> console. writeline ("{0 }:{ 1}", key, istudent [Key]);
    }

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.