WinForm修改App.config設定檔功能

來源:互聯網
上載者:User

標籤:app-config   組態管理   配置資訊   getsection   

WinForm修改App.config設定檔主要是通過System.Configuration.dll裡ConfigurationManager類來實現,在功能開發前是需要手動引用該dll檔案。

ConfigurationManager 類包括可用來執行以下任務的成員:
?從設定檔中讀取一個節。若要訪問配置資訊,請調用 GetSection 方法。對於某些節,例如 appSettings 和 connectionStrings,請使用 AppSettings 和 ConnectionStrings 類。這些成員執行唯讀操作,使用配置的單個緩衝執行個體,並且可識別多線程。

?將設定檔作為一個整體進行讀取和寫入。應用程式能夠讀寫任何層級的配置設定,不管是自己的還是其他應用程式或電腦的,也不管是本地的還是遠端。使用 ConfigurationManager 類提供的方法之一,可開啟設定檔,例如 SampleApp.exe.config。這些方法返回一個 Configuration 對象,該對象進而公開您可以用來處理關聯設定檔的方法和屬性。這些方法執行讀取或寫入操作,並於每次寫入檔案時建立配置資料。

?支援配置任務。
下列類型用於支援各種配置任務:
SectionInformation
PropertyInformation
PropertyInformationCollection
ElementInformation
ContextInformation
ConfigurationSectionGroup
ConfigurationSectionGroupCollection

除了處理現有的配置資訊外,還可以通過擴充內建的配置類型(如 ConfigurationElement、ConfigurationElementCollection、ConfigurationProperty 和 ConfigurationSection 類),來建立和處理自訂配置元素。有關如何以編程方式擴充內建配置類型的樣本,請參見 ConfigurationSection。有關如何擴充內建配置類型(該內建配置類型使用基於特性的模型)的樣本,請參見 ConfigurationElement。

對實現者的說明
Configuration 類允許進行編程訪問以編輯設定檔。使用 ConfigurationManager 提供的 Open 方法中的一種。這些方法返回一個 Configuration 對象,該對象又提供處理基礎設定檔所需的方法和屬性。您可以訪問這些檔案以進行讀取或寫入。

若要讀取設定檔,請使用 GetSection 或 GetSectionGroup 讀取配置資訊。進行讀取的使用者或過程必須具有下面的許可權:
?在當前配置階層層級下對設定檔的讀取許可權。
?對所有父級設定檔進行讀取的許可權。

如果應用程式需要對它自己的配置進行唯讀訪問,我們建議使用 GetSection 方法。此方法提供對當前應用程式的緩衝配置值的訪問,它的效能比 Configuration 類更好。

若要寫入設定檔,請使用 Save 方法中的一種。進行寫入的使用者或進程必須具有下面的許可權:
?對配置階層中當前層級的設定檔和目錄的寫入許可權。
?對所有設定檔的讀取許可權。

功能實現功能圖

功能實現代碼:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Configuration;using System.Data.SqlClient;using System.Security.AccessControl;using System.IO;namespace Tools.App{    public partial class UpApp : Form    {        public string ConnString = ConfigurationManager.AppSettings["ConnString"].ToString().Trim();        //日誌記錄路徑        public string LogPath = ConfigurationManager.AppSettings["LogPath"].ToString().Trim();        //執行時間間隔        public double Time = double.Parse(ConfigurationManager.AppSettings["Time"].ToString().Trim());        //組建檔案路徑        public string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString().Trim();        public string BackupPath = 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(object sender, EventArgs e)        {        }        /// <summary>        /// Description:          /// 確認事件          /// Author  : 付義方          /// Create Date: 2014-02-09         /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnSave_Click(object sender, 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");                string FilePath = this.txtFilePath.Text.Trim();                string LogPath = this.txtLogPath.Text.Trim();                string Time = this.txtTime.Text.Trim();                string ConnString = this.txtConnString.Text.Trim();                string BackupPath = 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);                //分配許可權                // 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("你修改了設定檔需要重啟程式!");                this.Close();            }            catch            {                MessageBox.Show("讀寫設定檔出錯,請檢查安裝目錄是否有讀寫權限。");            }        }        /// <summary>        /// 為建立的臨時檔案分配許可權        /// </summary>        /// <param name="pathname"></param>        /// <param name="username"></param>        /// <param name="power"></param>        /// <remarks>SKY 2007-8-6</remarks>        public void addpathPower(string pathname, string username, string power)        {            DirectoryInfo dirinfo = new DirectoryInfo(pathname);            if ((dirinfo.Attributes & FileAttributes.ReadOnly) != 0)            {                dirinfo.Attributes = FileAttributes.Normal;            }            //取得存取控制清單            DirectorySecurity dirsecurity = dirinfo.GetAccessControl();            switch (power)            {                case "FullControl":                    dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));                    break;                case "ReadOnly":                    dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Read, AccessControlType.Allow));                    break;                case "Write":                    dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Write, AccessControlType.Allow));                    break;                case "Modify":                    dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Modify, AccessControlType.Allow));                    break;            }        }        private void btnClose_Click(object sender, EventArgs e)        {            this.Close();        }        private void btnTest_Click(object sender, EventArgs e)        {            SqlConnection _SqlConnection = new SqlConnection(this.txtConnString.Text.Trim());            try            {                _SqlConnection.Open();                MessageBox.Show("資料庫連接成功!", "恭喜", MessageBoxButtons.OK, MessageBoxIcon.Information);            }            catch (Exception)            {                MessageBox.Show("不能串連資料庫,請重新設定!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);                return;            }            finally            {                _SqlConnection.Close();            }        }        private void button1_Click(object sender, EventArgs e)        {            string FilePath = this.txtFilePath.Text.Trim();            string LogPath = this.txtLogPath.Text.Trim();            string BackupPath = 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("執行成功!", "提示");        }    }}

希望以上分享對初學朋友有些協助,謝謝!
更多關注付義方技術部落格:http://blog.csdn.net/fuyifang
或者直接用手機掃描二維碼查看更多博文:

WinForm修改App.config設定檔功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.