C#读写Config配置文件案例

一、简介

应用程序配置文件(App.config)是标准的 XML 文件,XML 标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序。

*.exe.config配置文件样式:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
  </connectionStrings>
  <appSettings>
    <add key="ServerIP" value="127.0.0.1"></add>
    <add key="DataBase" value="WarehouseDB"></add>
    <add key="user" value="sa"></add>
    <add key="password" value="sa"></add>
  </appSettings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

二、代码

1.配置文件读写类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration;
using System.ServiceModel;
using System.ServiceModel.Configuration;

namespace XMLDemo1
{
    public static class ConfigHelper
    {
        #region ConnectionStrings
        //依据连接串名字connectionName返回数据连接字符串
        public static string GetConnectionStringsConfig(string connectionName)
        {
            //指定config文件读取
            string file = System.Windows.Forms.Application.ExecutablePath;
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            string connectionString =
                config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString();
            return connectionString;
        }

        ///<summary>
        ///更新连接字符串
        ///</summary>
        ///<param name="newName">连接字符串名称</param>
        ///<param name="newConString">连接字符串内容</param>
        ///<param name="newProviderName">数据提供程序名称</param>
        public static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)
        {
            //指定config文件读取
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);

            bool exist = false; //记录该连接串是否已经存在
            //如果要更改的连接串已经存在
            if (config.ConnectionStrings.ConnectionStrings[newName] != null)
            {
                exist = true;
            }
            // 如果连接串已存在,首先删除它
            if (exist)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            //新建一个连接字符串实例
            ConnectionStringSettings mySettings =
                new ConnectionStringSettings(newName, newConString, newProviderName);
            // 将新的连接串添加到配置文件中.
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节
            ConfigurationManager.RefreshSection("ConnectionStrings");
        }

        #endregion

        #region appSettings
        ///<summary>
        ///返回*.exe.config文件中appSettings配置节的value项
        ///</summary>
        ///<param name="strKey"></param>
        ///<returns></returns>
        public static string GetAppConfig(string strKey)
        {
            //D:\Winform\xml文档操作\XMLDemo1\bin\Debug\XMLDemo1.EXE
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value.ToString();
                }
            }
            return null;
        }

        ///<summary>
        ///在*.exe.config文件中appSettings配置节增加一对键值对
        ///</summary>
        ///<param name="newKey"></param>
        ///<param name="newValue"></param>
        public static void UpdateAppConfig(string newKey, string newValue)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            bool exist = false;
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == newKey)
                {
                    exist = true;
                }
            }
            if (exist)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            config.AppSettings.Settings.Add(newKey, newValue);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        #endregion

        #region
        // 修改system.serviceModel下所有服务终结点的IP地址
        public static void UpdateServiceModelConfig(string configPath, string serverIP)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
            ConfigurationSectionGroup sec = config.SectionGroups["system.serviceModel"];
            ServiceModelSectionGroup serviceModelSectionGroup = sec as ServiceModelSectionGroup;
            ClientSection clientSection = serviceModelSectionGroup.Client;
            foreach (ChannelEndpointElement item in clientSection.Endpoints)
            {
                string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
                string address = item.Address.ToString();
                string replacement = string.Format("{0}", serverIP);
                address = Regex.Replace(address, pattern, replacement);
                item.Address = new Uri(address);
            }

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("system.serviceModel");
        }

        // 修改applicationSettings中App.Properties.Settings中服务的IP地址
        public static void UpdateConfig(string configPath, string serverIP)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
            ConfigurationSectionGroup sec = config.SectionGroups["applicationSettings"];
            ConfigurationSection configSection = sec.Sections["DataService.Properties.Settings"];
            ClientSettingsSection clientSettingsSection = configSection as ClientSettingsSection;
            if (clientSettingsSection != null)
            {
                SettingElement element1 = clientSettingsSection.Settings.Get("DataService_SystemManagerWS_SystemManagerWS");
                if (element1 != null)
                {
                    clientSettingsSection.Settings.Remove(element1);
                    string oldValue = element1.Value.ValueXml.InnerXml;
                    element1.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP);
                    clientSettingsSection.Settings.Add(element1);
                }

                SettingElement element2 = clientSettingsSection.Settings.Get("DataService_EquipManagerWS_EquipManagerWS");
                if (element2 != null)
                {
                    clientSettingsSection.Settings.Remove(element2);
                    string oldValue = element2.Value.ValueXml.InnerXml;
                    element2.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP);
                    clientSettingsSection.Settings.Add(element2);
                }
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("applicationSettings");
        }

        private static string GetNewIP(string oldValue, string serverIP)
        {
            string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
            string replacement = string.Format("{0}", serverIP);
            string newvalue = Regex.Replace(oldValue, pattern, replacement);
            return newvalue;
        }
        #endregion
    }
}

2.Main 函数

namespace XMLDemo1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //D:\Winform\xml文档操作\XMLDemo1\bin\Debug\XMLDemo1.EXE
                //string file0 = System.Windows.Forms.Application.ExecutablePath;
                //D:\Winform\xml文档操作\XMLDemo1\bin\Debug\XMLDemo1.EXE.config
                //string file = System.Windows.Forms.Application.ExecutablePath + ".config";
                //D:\Winform\xml文档操作\XMLDemo1\bin\Debug\XMLDemo1.vshost.exe.Config
                //string file1 = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

                string serverIP = ConfigHelper.GetAppConfig("ServerIP");
                string db = ConfigHelper.GetAppConfig("DataBase");
                string user = ConfigHelper.GetAppConfig("user");
                string password = ConfigHelper.GetAppConfig("password");

                Console.WriteLine(serverIP);
                Console.WriteLine(db);
                Console.WriteLine(user);
                Console.WriteLine(password);

                ConfigHelper.UpdateAppConfig("ServerIP", "192.168.0.1");
                string newIP = ConfigHelper.GetAppConfig("ServerIP");
                Console.WriteLine(newIP);
                ConfigHelper.UpdateConnectionStringsConfig("connstr4", ".......", "System.Data.Sqlclient");

                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

到此这篇关于C#读写Config配置文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • C#获取web.config配置文件内容的方法

    本文实例讲述了C#获取web.config配置文件内容的方法.分享给大家供大家参考.具体实现方法如下: 1.ConfigurationManager提供对客户端应用程序配置文件的访问. 其有两个属性:ConnectionStrings 获取当前应用程序默认配置的 ConnectionStringsSection 数据. 方法一: 复制代码 代码如下: string myConn =System.Configuration.ConfigurationManager.ConnectionString

  • 通过C#程序操作Config文件

    对于config文件,一般情况下都是使用ConfigurationManager加载,然后通过读取相应节点的值来获取想要的数据,但是,有时候需要修改config文件的值,这时候就用到了OpenExeConfiguration()方法. MSDN上面对该方法的解释:ConfigurationManager.OpenExeConfiguration方法用来把指定的客户端配置文件作为Configuration对象打开,该方法具有两个重载: 名称 说明 ConfigurationManager.Open

  • C#中读取App.config配置文件代码实例

    App.config是C#开发WinForm程序的配置文件,开发Web程序的配置文件叫Web.config.本文介绍App.config的简介使用. 我们先来打开一个App.config文件,看看它的内容像什么样子. <?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="conn" co

  • ASP.NET(C#)应用程序配置文件app.config/web.config的增、删、改操作

    配置文件,对于程序本身来说,就是基础和依据,其本质是一个xml文件,对于配置文件的操作,从.NET 2.0 开始,就非常方便了,提供了 System [.Web] .Configuration 这个管理功能的NameSpace,要使用它,需要添加对 System.configuration.dll的引用. 对于WINFORM程序,使用 System.Configuration.ConfigurationManager: 对于ASP.NET 程序, 使用 System.Web.Configurat

  • C#读写config配置文件的方法

    如下所示: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="ServerIP" value="127.0.0.1"></add> <add key="DataBase" value="WarehouseDB"&g

  • c# 配置文件App.config操作类库的方法

    实例如下: public class ConfigOperator { #region 从配置文件获取Value /// <summary> /// 从配置文件获取Value /// </summary> /// <param name="key">配置文件中key字符串</param> /// <returns></returns> public static string GetValueFromConfig(

  • 详解C#如何读写config配置文件

    配置文件概述: 应用程序配置文件是标准的 XML 文件,XML 标记和属性是区分大小写的.它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序.配置文件的根节点是configuration.我们经常访问的是appSettings,它是由.Net预定义的配置节.我们经常使用的配置文件的架构是客诉下面的形式.先大概有个印象,通过后面的实例会有一个比较清楚的认识.下面的"配置节"可以理解为进行配置一个XML的节点. 对于一个config文件: <?xml ve

  • C#操作config文件的具体方法

    以下是app.config或web.config的定义,定义了一个参数,键为Isinit,值为false<?xml version="1.0"?> <configuration> <appSettings> <add key ="IsInit" value="false"/> </appSettings> </configuration> 以下是读和写config文件的方法定

  • C# 添加对System.Configuration.dll文件的引用操作

    却被编译器提示说: 警告 1 "System.Configuration.ConfigurationSettings.AppSettings" 已过时: "This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings" 于是转而想找到那个ConfigurationManager类来使

  • C#读写Config配置文件案例

    一.简介 应用程序配置文件(App.config)是标准的 XML 文件,XML 标记和属性是区分大小写的.它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序. *.exe.config配置文件样式: <?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> </connectionStrings>

  • 详解在.net中读写config文件的各种方法

    今天谈谈在.net中读写config文件的各种方法. 在这篇博客中,我将介绍各种配置文件的读写操作. 由于内容较为直观,因此没有过多的空道理,只有实实在在的演示代码, 目的只为了再现实战开发中的各种场景.希望大家能喜欢. 通常,我们在.NET开发过程中,会接触二种类型的配置文件:config文件,xml文件. 今天的博客示例也将介绍这二大类的配置文件的各类操作. 在config文件中,我将主要演示如何创建自己的自定义的配置节点,而不是介绍如何使用appSetting . 请明:本文所说的conf

  • Python实现读写INI配置文件的方法示例

    本文实例讲述了Python实现读写INI配置文件的方法.分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- import ConfigParser import os '''读写配置文件的类 [section] logpath = D:\log\ imageminsize = 200 ''' class ConfigFile: '''构造函数:初始化''' def __init__(self,fileName): fileName = unicode(fileNam

  • C#中读写INI配置文件的方法

    在作应用系统开发时,管理配置是必不可少的.例如数据库服务器的配置.安装和更新配置等等.由于Xml的兴起,现在的配置文件大都是以xml文档来存储.比如Visual Studio.Net自身的配置文件Mashine.config,Asp.Net的配置文件Web.Config,包括我在介绍Remoting中提到的配置文件,都是xml的格式. 传统的配置文件ini已有被xml文件逐步代替的趋势,但对于简单的配置,ini文件还是有用武之地的.ini文件其实就是一个文本文件,它有固定的格式,节Section

  • Python3读写ini配置文件的示例

    ini文件即Initialization File初始化文件,在应用程序及框架中常作为配置文件使用,是一种静态纯文本文件,使用记事本即可编辑. 配置文件的主要功能就是存储一批变量和变量值,在ini文件中使用[章(Section)]对变量进行了分组,基本格式如下. # filename: config.ini [user] name=admin password=123456 is_admin=true [mysql] host=10.10.10.10 port=3306 db=apitest u

  • Java SSM配置文件案例详解

    先对Spring SpringMVC和Mybatis单独进行配置,最后对三者进行整合配置 Spring 实际使用中,一般会使用注解+xml配置来实现spring功能,其中xml配置对上文进行总结,配置内容如下 <?xml version="1.0" encoding="UTF-8"?> <!--在使用spring 相关jar包的时候进行配置 每个jar包对应一个xmlns和schemaLocation路径--> <!--格式基本相关 只

  • QT中如何读写ini配置文件

    如图1所示,我们需要在QT界面中实现手动读取参数存放的位置,那么我们该如何做呢? 方法:读取ini格式的配置文件,实现路径的写入与读取. 第一步:界面构造函数中,初始化一个Config.ini文件 //初始化一个.ini配置文件 //qApp是QT系统自带的,可以直接使用 QString iniFilePath=qApp->applicationDirPath()+"/Config.ini"; //如果不存在Config.ini,便生成一个Config.ini.如果已经存在了,则

  • Java 读写Properties配置文件详解

    Java 读写Properties配置文件 1.Properties类与Properties配置文件 Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集.不过Properties有特殊的地方,就是它的键和值都是字符串类型. 2.Properties中的主要方法 (1)load(InputStream inStream) 这个方法可以从.properties属性文件对应的文件输入流中,加载属性列表到Properties类对象.如下面的代码:

随机推荐