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博客二维码

目录
相关文章
|
2月前
文件名: ?Ciwindows\system32 inetsrconfiglapplicationHost.config 错误:无法写入配置文件
文件名: ?Ciwindows\system32 inetsrconfiglapplicationHost.config 错误:无法写入配置文件
43 0
|
6天前
|
移动开发 Android开发 数据安全/隐私保护
移动应用与系统的技术演进:从开发到操作系统的全景解析随着智能手机和平板电脑的普及,移动应用(App)已成为人们日常生活中不可或缺的一部分。无论是社交、娱乐、购物还是办公,移动应用都扮演着重要的角色。而支撑这些应用运行的,正是功能强大且复杂的移动操作系统。本文将深入探讨移动应用的开发过程及其背后的操作系统机制,揭示这一领域的技术演进。
本文旨在提供关于移动应用与系统技术的全面概述,涵盖移动应用的开发生命周期、主要移动操作系统的特点以及它们之间的竞争关系。我们将探讨如何高效地开发移动应用,并分析iOS和Android两大主流操作系统的技术优势与局限。同时,本文还将讨论跨平台解决方案的兴起及其对移动开发领域的影响。通过这篇技术性文章,读者将获得对移动应用开发及操作系统深层理解的钥匙。
|
2月前
|
Java PHP
【应用服务 App Service】 App Service Rewrite 实例 - 反向代理转发功能
【应用服务 App Service】 App Service Rewrite 实例 - 反向代理转发功能
【应用服务 App Service】 App Service Rewrite 实例 - 反向代理转发功能
|
2月前
|
Python
【Azure 应用服务】App Service的运行状况检查功能失效,一直提示"实例运行不正常"
【Azure 应用服务】App Service的运行状况检查功能失效,一直提示"实例运行不正常"
|
4月前
|
开发框架 移动开发 JavaScript
SpringCloud微服务实战——搭建企业级开发框架(四十七):【移动开发】整合uni-app搭建移动端快速开发框架-添加Axios并实现登录功能
在uni-app中,使用axios实现网络请求和登录功能涉及以下几个关键步骤: 1. **安装axios和axios-auth-refresh**: 在项目的`package.json`中添加axios和axios-auth-refresh依赖,可以通过HBuilderX的终端窗口运行`yarn add axios axios-auth-refresh`命令来安装。 2. **配置自定义常量**: 创建`project.config.js`文件,配置全局常量,如API基础URL、TenantId、APP_CLIENT_ID和APP_CLIENT_SECRET等。
206 60
|
2月前
|
测试技术
一款功能完善的智能匹配1V1视频聊天App应该通过的测试CASE
文章列举了一系列针对1V1视频聊天App的测试用例,包括UI样式、权限请求、登录流程、匹配逻辑、消息处理、充值功能等多个方面的测试点,并标注了每个测试用例的执行状态,如通过(PASS)、失败(FAIL)或需要进一步处理(延期修改、待定、方案再定等)。
39 0
|
2月前
|
Linux C++ Docker
【Azure 应用服务】App Service for Linux 中实现 WebSocket 功能 (Python SocketIO)
【Azure 应用服务】App Service for Linux 中实现 WebSocket 功能 (Python SocketIO)
|
2月前
|
监控 安全 前端开发
【Azure 应用服务】App Service 运行状况健康检查功能简介 (Health check)
【Azure 应用服务】App Service 运行状况健康检查功能简介 (Health check)
|
3月前
|
存储 前端开发 测试技术
同城交友APP系统开发运营版/案例详细/功能步骤/逻辑方案
开发一款同城交友APP系统需要经过以下大致流程:
|
3月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue+uniapp的多功能智能手机阅读APP的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue+uniapp的多功能智能手机阅读APP的详细设计和实现(源码+lw+部署文档+讲解等)
下一篇
无影云桌面