WinForm修改App.config配置文件功能

简介: WinForm修改App.config配置文件主要是通过System.Configuration.dll里ConfigurationManager类来实现,在功能开发前是需要手动引用该dll文件。

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
或者直接用手机扫描二维码查看更多博文:
付义方CSDN博客二维码

目录
相关文章
|
1月前
uni-app 155朋友圈评论功能(二)
uni-app 155朋友圈评论功能(二)
40 0
|
1月前
uni-app 152朋友圈动态实时通知功能
uni-app 152朋友圈动态实时通知功能
17 0
|
1月前
uni-app 122转发功能实现(二)
uni-app 122转发功能实现(二)
16 0
|
1月前
uni-app 121转发功能实现(一)
uni-app 121转发功能实现(一)
18 0
|
1月前
|
Java 数据库连接 mybatis
Mybatis+mysql动态分页查询数据案例——Mybatis的配置文件(mybatis-config.xml)
Mybatis+mysql动态分页查询数据案例——Mybatis的配置文件(mybatis-config.xml)
20 1
|
1月前
uni-app 179转发名片功能
uni-app 179转发名片功能
18 1
|
1月前
uni-app 154朋友圈评论功能(一 )
uni-app 154朋友圈评论功能(一 )
13 0
|
1月前
uni-app 162初始化会话列表功能
uni-app 162初始化会话列表功能
11 0
|
1月前
uni-app 160提醒谁看功能
uni-app 160提醒谁看功能
10 0
|
1月前
|
存储 数据库
uni-app 156朋友圈评论表情包功能
uni-app 156朋友圈评论表情包功能
45 0