ASP. NET read and modify config file implementation code

Source: Internet
Author: User
Tags connectionstrings
To add an app. Config file to your project:

Right-click the project name, choose Add → add new item, and in the Add New Item dialog box that appears, select Add Application profile, or if the project has not previously had a profile, the default file name is App. config and click OK. The app. config file that appears in 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 (for this project, for example), one named "JxcManagement.EXE.config" and another named "JxcManagement.vshost.exe.config ”。 The first file is the configuration file that is actually used by the project, and the changes made in the program run are saved here, and the second file is the original code "app. Config" synchronization file, which does not change during program run.
2. ConnectionStrings configuration section:
NOTE: If your SQL version is 2005 Express, the SQL Server instance named Localhost\sqlexpress is installed by default and must be changed in the following instance "Data Source=localhost;" The word "Data source=localhost\sqlexpress;", do not add an overhead grid on either side of the equals sign.
<!--database connection string--

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

AppSettings configuration section:
The appsettings configuration section is a configuration for the entire program, and if it is a configuration for the current user, use the UserSettings configuration section in the same format as the following configuration writing requirements.
<!--Invoicing Management system initialization required parameters--

<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
For read-write to the app. Config file, refer to the network article: http://www.codeproject.com/csharp/SystemConfiguration.asp titled "Read/write App. Config File with. NET 2.0 "article.
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 the reference system.configuration.
4.1 Reading the connectionstrings configuration section

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

4.2 Update connectionstrings configuration section

<summary>//Update connection string///</summary>///<param name= "NewName" > Connection string name </param>///<param Name= "newconstring" > Connection string Contents </param>///<param name= "Newprovidername" > Data provider name </param> private static void Updateconnectionstringsconfig (String newName, String newconstring, String newprovidername) {bool IsM Odified = false; Record if the connection string already exists//if the connection string you want to change 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, first remove it if (ismodified) {config. ConnectionStrings.ConnectionStrings.Remove (NewName); }//Adds a new connection string to the configuration file. Config. CONNECTIONSTRINGS.CONNECTIONSTRINGS.ADD (mysettings); Save the changes you made to the configuration file CONFIG. Save (configurationsavemode.modified); Force the connectionstrings configuration section of the configuration file to be re-loaded ConfigurAtionmanager.refreshsection ("ConnectionStrings"); }

4.3 Reading the Appstrings configuration section

<summary>///Returns the value of 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) {return configurationmanager.appsettings[strkey];}} retur n null; }

4.4 Update connectionstrings configuration section

///<summary>///*.exe.config configuration section in appsettings file add a pair of keys, value pairs///</summary >///<param name= "NewKey" ></param>///<param name= "newvalue" ></param> private static void Updateappconfig (String NewKey, string newvalue) {bool ismodified = false; foreach (string key in Configurationmanager.app Settings) {if (Key==newkey) {ismodified = true;}}//Open app. Config of executable configuration config = Configuration Manager.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"); }
<summary>///write Key,value to XML file///</summary>//<param name= "Key" ></param>///<param N Ame= "value" ></param> public static void Saveconfig (String key,string Value) {XmlDocument doc = new XmlDocument () ; Get the full path of the configuration file string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString () + "app. 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 = = Key) {//assigns ATT = nodes[i] to the second attribute in the target element. attributes["value"]; Att. Value = value; Break }}//Save the above modification doc. Save (strFileName); }


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.