WinForm Modifying the App. Config Profile feature

Source: Internet
Author: User
Tags configuration settings connectionstrings

WinForm Modifying the app. config configuration file is implemented primarily through the System.Configuration.dll ConfigurationManager class, which is required to manually reference the DLL file prior to feature development.

The ConfigurationManager class includes members that you can use to perform the following tasks:
? reads a section from the configuration file. To access configuration information, call the GetSection method. For some sections, such as AppSettings and connectionStrings, use the AppSettings and ConnectionStrings classes. These members perform read-only operations, use a single cached instance of the configuration, and can recognize multithreading.

? Read and write the configuration file as a whole. The application can read and write any level of configuration settings, whether it is its own or another application or computer, whether local or remote. Use one of the methods provided by the ConfigurationManager class to open a configuration file, such as SampleApp.exe.config. These methods return a configuration object that exposes the methods and properties that you can use to work with the associated configuration file. These methods perform read or write operations, and create configuration data each time the file is written.

? support configuration Tasks.
The following types are used to support various configuration tasks:
Sectioninformation
Propertyinformation
Propertyinformationcollection
Elementinformation
Contextinformation
ConfigurationSectionGroup
Configurationsectiongroupcollection

In addition to processing existing configuration information, you can also extend the built-in configuration types such as ConfigurationElement, ConfigurationElementCollection, ConfigurationProperty, and ConfigurationSection Class) to create and process custom configuration elements. For an example of how to programmatically extend the built-in configuration type, see ConfigurationSection. For an example of how to extend the built-in configuration type, which uses the attribute-based model, see ConfigurationElement.

Description of the person who implemented it
The configuration class allows programmatic access to edit the config file. Use one of the Open methods provided by ConfigurationManager. These methods return a configuration object that provides the methods and properties required to process the underlying configuration file. You can access these files for reading or writing.

To read the configuration file, use GetSection or Getsectiongroup to read the configuration information. The user or procedure that is reading must have the following permissions:
? Read permissions to the profile at the current configuration hierarchy level.
The permission to read all the parent configuration files.

If your application needs read-only access to its own configuration, we recommend that you use the GetSection method. This method provides access to the cache configuration values of the current application, which performs better than the Config class.

To write to a configuration file, use one of the Save methods. The user or process that is writing must have the following permissions:
? Write permission to the configuration file and directory at the current level in the configuration hierarchy.
? Read permissions for all profiles.

function Realization function diagram

Feature Implementation code:

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Configuration;usingSystem.Data.SqlClient;usingSystem.Security.AccessControl;usingSystem.io;namespace tools.app{ Public Partial classUpapp:form { Public stringconnstring = configurationmanager.appsettings["ConnString"]. ToString (). Trim ();//logging Path         Public stringLogPath = configurationmanager.appsettings["LogPath"]. ToString (). Trim ();//Execution time interval         Public DoubleTime =Double. Parse (configurationmanager.appsettings["Time"]. ToString (). Trim ());//Generate file path         Public stringFilePath = configurationmanager.appsettings["FilePath"]. ToString (). Trim (); Public stringBackuppath = configurationmanager.appsettings["Backuppath"]. ToString (). Trim (); Public Upapp() {InitializeComponent (); This. Txtconnstring.text = connstring; This. Txtfilepath.text = FilePath; This. Txtlogpath.text = LogPath; This. Txttime.text = Time.tostring (); This. Txtbackuppath.text = Backuppath.tostring (); }Private void Upapp_load(Objectsender, EventArgs e) {}//   <summary>           ///Description:        ///   Confirmation Event          ///Author: Hui Yifang        //   Create date:2014-02-09        //   </summary>         ///   <param name= "sender" ></param>         ///   <param name= "E" ></param>         Private void Btnsave_click(Objectsender, EventArgs e) {Try{Configuration config = configurationmanager.openexeconfiguration (configurationuserlevel.none); Config. AppSettings.Settings.Remove ("FilePath"); Config. AppSettings.Settings.Remove ("LogPath"); Config. AppSettings.Settings.Remove ("Time"); Config. AppSettings.Settings.Remove ("ConnString"); Config. AppSettings.Settings.Remove ("Backuppath");stringFilePath = This. TxtFilePath.Text.Trim ();stringLogPath = This. TxtLogPath.Text.Trim ();stringTime = This. TxtTime.Text.Trim ();stringConnString = This. TxtConnString.Text.Trim ();stringBackuppath = This. TxtBackupPath.Text.Trim (); Config. APPSETTINGS.SETTINGS.ADD ("FilePath", FilePath); Config. APPSETTINGS.SETTINGS.ADD ("Time", time); Config. APPSETTINGS.SETTINGS.ADD ("LogPath", LogPath); Config. APPSETTINGS.SETTINGS.ADD ("ConnString", connstring); Config. APPSETTINGS.SETTINGS.ADD ("Backuppath", backuppath);//Assign Permissions                //MessageBox.Show (config. Filepath.replace (@ "\tools.app.exe.config", ""));Addpathpower (config. Filepath.replace (@ "\tools.app.exe.config",""),"Everyone","FullControl"); Config.                Save (); Configurationmanager.refreshsection ("AppSettings"); MessageBox.Show ("You have modified the configuration file to restart the program!" "); This.            Close (); }Catch{MessageBox.Show ("There was an error reading and writing the configuration file, please check the installation directory for read and write permissions. "); }        }//   <summary>         ///   Assign permissions for temporary files created        //   </summary>         ///   <param name= "pathname" ></param>         ///   <param name= "username" ></param>         ///   <param name= "Power" ></param>         ///   <remarks>SKY 2007-8-6</remarks>          Public void Addpathpower(stringPathnamestringUsernamestringPower) {DirectoryInfo Dirinfo =NewDirectoryInfo (pathname);if(Dirinfo. Attributes & fileattributes.readonly)! =0) {Dirinfo.            Attributes = Fileattributes.normal; }//Get access Control ListDirectorySecurity dirsecurity = Dirinfo. GetAccessControl ();Switch(Power) { Case "FullControl": Dirsecurity. Addaccessrule (NewFileSystemAccessRule (username, Filesystemrights.fullcontrol, Inheritanceflags.containerinherit, Propagationflags.inheritonly, Accesscontroltype.allow)); Break; Case "ReadOnly": Dirsecurity. Addaccessrule (NewFileSystemAccessRule (username, filesystemrights.read, accesscontroltype.allow)); Break; Case "Write": Dirsecurity. Addaccessrule (NewFileSystemAccessRule (username, filesystemrights.write, accesscontroltype.allow)); Break; Case "Modify": Dirsecurity. Addaccessrule (NewFileSystemAccessRule (username, filesystemrights.modify, accesscontroltype.allow)); Break; }        }Private void btnClose_Click(Objectsender, EventArgs e) { This.        Close (); }Private void btnTest_Click(Objectsender, EventArgs e) {SqlConnection _sqlconnection =NewSqlConnection ( This. TxtConnString.Text.Trim ());Try{_sqlconnection.open (); MessageBox.Show ("The database connection was successful!" ","Congratulations.", MessageBoxButtons.OK, MessageBoxIcon.Information); }Catch(Exception) {MessageBox.Show ("Unable to connect to the database, please reset it!" ","Warning", MessageBoxButtons.OK, messageboxicon.warning);return; }finally{_sqlconnection.close (); }        }Private void Button1_Click(Objectsender, EventArgs e) {stringFilePath = This. TxtFilePath.Text.Trim ();stringLogPath = This. TxtLogPath.Text.Trim ();stringBackuppath = This. TxtBackupPath.Text.Trim ();if(!            Directory.Exists (FilePath)) {directory.createdirectory (FilePath); }if(!            Directory.Exists (LogPath)) {directory.createdirectory (LogPath); }if(!            Directory.Exists (Backuppath)) {directory.createdirectory (backuppath); } MessageBox.Show ("Successful Execution!" ","Hint"); }    }}

Hope that the above share of the beginner friends some help, thank you!
More Attention Fuyi Technology blog: Http://blog.csdn.net/fuyifang
or scan the QR code directly with your phone to see more Posts:

WinForm Modifying the App. Config Profile feature

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.