. NET

Source: Internet
Author: User
Tags connectionstrings

In. net programming, we often use the config file to save some common application configuration information. In WinForm, the file name is app. config and is called web. config in asp.net. This. config file is actually an xml file. Microsoft has provided a class for its read operations. This class is System. Configuration. ConfigurationManager. The following are examples:
// Read the connection information of the database named "conn" in config.
ConnectionString = System. Configuration. ConfigurationManager. ConnectionStrings ["conn"]. ConnectionString;
// Read the application configuration information named "Font_Size" in config
System. Configuration. ConfigurationManager. receivettings ["Font-Size"] = 9;
However, this class cannot be used to write the config file. For write operations on the config file, many people use the xml method. Write operations based on the xml method are cumbersome in WinForm, but can be completed after all. The following is an example of writing data according to an xml file.

# Region save Configuration
XmlDocument document = LoadXml ();
XmlNode root = document. DocumentElement;
XmlNodeList nodeList = root. FirstChild. ChildNodes;
For (int I = 0; I <nodeList. Count; I ++)
{
String key = nodeList [I]. Attributes ["key"]. Value;
If (key = "FilterOption ")
{
NodeList [I]. Attributes ["value"]. Value = (int) container. FilterOption). ToString ();
}
}
Document. Save (configPath );
# Endregion

However, in WebForm, errors are often reported due to insufficient permissions.

This article provides another way to use the Configuration in the. net2.0 class library for write operations. For more information, see the following.

Configuration is a class that allows programmatic access to edit Configuration files. For the WebForm config file, you can use the following code to obtain an instance of the Configuration class:
Configuration config = System. Web. Configuration. WebConfigurationManager. OpenWebConfiguration (configPath );
For the config file of WinForm, you can use the following code to obtain an instance of the Configuration class:

Configuration config = System. Configuration. ConfigurationManager. OpenExeConfiguration (configPath );
Note that, after writing an object, you must call the Save () method to Save the result. The source code of the entire program is as follows, with detailed code comments.

Using System;
Using System. Configuration;
Using System. Web;
Using System. Windows. Forms;

Namespace NetSkycn. Common
{
/// <Summary>
/// Description: enumeration of Config file types,
/// The config file of the asp.net website and the config file of WinForm respectively
/// By Zhou Gong
/// Date: 2008-08-23
/// Starting address: http://blog.csdn.net/zhoufoxcn/archive/2008/08/24/2823508.aspx
/// </Summary>
Public enum ConfigType
{
/// <Summary>
/// The config file of the asp.net website
/// </Summary>
WebConfig = 1,
/// <Summary>
/// Config file of the Windows Application
/// </Summary>
ExeConfig = 2
}

/// <Summary>
/// Description: This class is mainly responsible for modifying the program configuration file (. config,
/// Modify the configuration file of the website and Application
/// By Zhou Gong
/// Date: 2008-08-23
/// Starting address: http://blog.csdn.net/zhoufoxcn/archive/2008/08/24/2823508.aspx
/// </Summary>
Public class ConfigurationOperator
{
Private Configuration config;
Private string configPath;
Private ConfigType configType;

/// <Summary>
/// Corresponding configuration file
/// </Summary>
Public Configuration
{
Get {return config ;}
Set {config = value ;}
}
/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "configType"> type of the. config file, which can only be a website configuration file or an application configuration file </param>
Public ConfigurationOperator (ConfigType configType)
{
This. configType = configType;
If (configType = ConfigType. ExeConfig)
{
ConfigPath = Application. ExecutablePath; // AppDomain. CurrentDomain. BaseDirectory;
}
Else
{
ConfigPath = HttpContext. Current. Request. ApplicationPath;
}
Initialize ();
}
/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "path"> location of the. config file </param>
/// <Param name = "type"> type of the. config file, which can only be a website configuration file or an application configuration file </param>
Public ConfigurationOperator (string configPath, ConfigType configType)
{
This. configPath = configPath;
This. configType = configType;
Initialize ();
}
// Instantiate configuration. Different instantiation methods are adopted based on different configuration file types.
Private void Initialize ()
{
// If it is a configuration file of the WinForm Application
If (configType = ConfigType. ExeConfig)
{
Config = System. Configuration. ConfigurationManager. OpenExeConfiguration (configPath );
}
Else // WebForm configuration file
{
Config = System. Web. Configuration. WebConfigurationManager. OpenWebConfiguration (configPath );
}
}

/// <Summary>
/// Add an application configuration node. If this node already exists, the value of this node is modified.
/// </Summary>
/// <Param name = "key"> node name </param>
/// <Param name = "value"> node value </param>
Public void adddeleetting (string key, string value)
{
AppSettingsSection paietting = (AppSettingsSection) config. GetSection ("appSettings ");
If (deleetting. Settings [key] = null) // if this node does not exist, add
{
Deleetting. Settings. Add (key, value );
}
Else // if this node exists, modify
{
Modifyreceivetting (key, value );
}
}
/// <Summary>
/// Add a database connection string node. If this node already exists, the value of this node is modified.
/// </Summary>
/// <Param name = "key"> node name </param>
/// <Param name = "value"> node value </param>
Public void AddConnectionString (string key, string connectionString)
{
ConnectionStringsSection connectionSetting = (ConnectionStringsSection) config. GetSection ("connectionStrings ");
If (connectionSetting. ConnectionStrings [key] = null) // if this node does not exist, add
{
ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings (key, connectionString );
ConnectionSetting. ConnectionStrings. Add (connectionStringSettings );
}
Else // if this node exists, modify
{
ModifyConnectionString (key, connectionString );
}
}
/// <Summary>
/// Modify the application configuration node. If this node does not exist, the node and the corresponding value are added.
/// </Summary>
/// <Param name = "key"> node name </param>
/// <Param name = "value"> node value </param>
Public void modifypolicetting (string key, string newValue)
{
AppSettingsSection paietting = (AppSettingsSection) config. GetSection ("appSettings ");
If (deleetting. Settings [key]! = Null) // if this node exists, modify
{
Deleetting. Settings [key]. Value = newValue;
}
Else // if this node does not exist, add
{
Addreceivetting (key, newValue );
}
}
/// <Summary>
/// Modify the database connection string node. If this node does not exist, the node and the corresponding value are added.
/// </Summary>
/// <Param name = "key"> node name </param>
/// <Param name = "value"> node value </param>
Public void ModifyConnectionString (string key, string connectionString)
{
ConnectionStringsSection connectionSetting = (ConnectionStringsSection) config. GetSection ("connectionStrings ");
If (connectionSetting. ConnectionStrings [key]! = Null) // if this node exists, modify
{
ConnectionSetting. ConnectionStrings [key]. ConnectionString = connectionString;
}
Else // if this node does not exist, add
{
AddConnectionString (key, connectionString );
}
}
/// <Summary>
/// Save the modification
/// </Summary>
Public void Save ()
{
Config. Save ();
}
}
}
 

Usage example:
(1) usage in WebForm

ConfigurationOperator co = new ConfigurationOperator (ConfigType. WebConfig );
String key = txtConnectionStringKey. Text;
String value = txtConnectionStringValue. Text;
Co. AddConnectionString (key, value );
Co. Save ();
(2) usage in WinForm

ConfigurationOperator co = new ConfigurationOperator (ConfigType. ExeConfig );
Co. addreceivetting ("Font-Size", "9 ");
Co. addreceivetting ("WebSite", "http://blog.csdn.net/zhoufoxcn ");
Co. AddConnectionString ("Connection", "test ");
Co. Save (); // Save the Write result
I added a blank app to WinForm. config file. After the above operations, the following results are obtained (this file is in the same directory as the last generated exe file, rather than the config file in the same folder as the source code ):

<? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Deleetask>
<Add key = "Font-Size" value = "9"/>
<Add key = "WebSite" value = "http://blog.csdn.net/zhoufoxcn"/>
</AppSettings>
<ConnectionStrings>
<Add name = "Connection" connectionString = "test"/>
</ConnectionStrings>
</Configuration>
After this encapsulation class, you can simplify the operations on the config Configuration file. You only need to specify whether the config file of the website or application is opened when instantiating the Configuration class instance, after all the modifications and additions are made, call the Save () method to Save the modifications. Note: To compile the above program as a class library, you must add references to the System. Web. dll, System. Windows. Forms. dll, and System. Configuration. dll class libraries.

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.