iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C#读写Config配置文件案例
  • 725
分享到

C#读写Config配置文件案例

2024-04-02 19:04:59 725人浏览 安东尼
摘要

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

一、简介

应用程序配置文件(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配置文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: C#读写Config配置文件案例

本文链接: https://www.lsjlt.com/news/146422.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C#读写Config配置文件案例
    一、简介 应用程序配置文件(App.config)是标准的 XML 文件,XML 标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用...
    99+
    2024-04-02
  • c++读写yaml配置文件
    目录YAML基础语法基本规则三种数据结构map,散列表list,数组scalar,纯量map嵌套mapmap嵌套listlist嵌套listlist嵌套map数据结构嵌套利用yaml...
    99+
    2023-05-14
    c++ 读写yaml配置文件 C++读写yaml文件 C++ yaml配置文件
  • c++怎么读写yaml配置文件
    这篇文章主要介绍“c++怎么读写yaml配置文件”,在日常操作中,相信很多人在c++怎么读写yaml配置文件问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”c++怎么读写yaml配置文件”的疑惑有所帮助!接下来...
    99+
    2023-07-05
  • C++实现读写ini配置文件的示例代码
    目录1.概述2.ini格式语法3.配置读取4.demo示例5.自动生成读取代码1.概述 配置文件的读取是每个程序必备的功能,配置文件的格式多种多样,例如:ini格式、json格式、x...
    99+
    2023-05-19
    C++读写ini配置文件 C++读写ini文件 C++ ini文件
  • java怎么读取config中的配置文件
    在Java中,可以使用Properties类来读取配置文件。下面是一个简单的示例: import java.io.FileInput...
    99+
    2024-02-29
    java
  • java怎么读取config目录下配置文件
    要读取config目录下的配置文件,可以使用Java中的Properties类来实现。首先,需要通过类加载器获取到配置文件的输入流。...
    99+
    2023-09-20
    java
  • C#读写自定义的Config文件的实现方法
    目录一、前言二、添加config文件三、读写配置文件一、前言 在软件开发中,经常用到设置这样的功能,如果设置中的功能不多,用 Json、XML 这样的数据结构存储非常的麻烦,一个字段...
    99+
    2024-04-02
  • c++开发中如何读写yaml配置文件
    目录c++ 开发中利用yaml-cpp读写yaml配置文件c++ 开发中利用yaml-cpp读写yaml配置文件 1、yaml-cpp 是一个开源库,地址在 github 上,htt...
    99+
    2023-05-14
    c++ yaml配置文件 c++ 读写 yaml配置文件
  • java 读写 ini 配置文件的示例代码
    下面通过代码先看下java 读写 ini 配置文件,代码如下所示: package org.fh.util; import java.io.BufferedReader; impo...
    99+
    2024-04-02
  • vue-cli配置文件之config的示例分析
    这篇文章主要介绍了vue-cli配置文件之config的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。首先我们先看一下config的...
    99+
    2024-04-02
  • c++开发中怎么读写yaml配置文件
    这篇文章主要讲解了“c++开发中怎么读写yaml配置文件”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“c++开发中怎么读写yaml配置文件”吧!c++ 开发中利用yaml-cpp读写yaml...
    99+
    2023-07-05
  • android读写文件怎么配置
    要在Android应用程序中读写文件,您需要在AndroidManifest.xml文件中进行一些配置。 首先,在AndroidM...
    99+
    2024-02-29
    android
  • qt怎么读写配置文件
    在Qt中,可以使用QSettings类来读写配置文件。QSettings类提供了简单的API来访问配置文件,无需考虑具体的配置文件格...
    99+
    2024-02-29
    qt
  • ssh之 ~/.ssh/config 配置文件实现
    文章目录 ~/.ssh/config配置实现常用的SSH配置项测试 ~/.ssh/config配置实现 参考 最常用的登陆方法是**ssh username@server -p por...
    99+
    2023-09-08
    ssh 服务器 运维
  • java读写ini配置文件的示例代码怎么编写
    本篇文章为大家展示了java读写ini配置文件的示例代码怎么编写,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。下面通过代码先看下java 读写 ini 配置文件,代码如下所示:package&nbs...
    99+
    2023-06-26
  • Python中怎么读写配置文件
    Python中怎么读写配置文件,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。python 读写配置文件ConfigParser模块是python自带的读取配置文件的模块.通...
    99+
    2023-06-17
  • 详解Spring-boot中读取config配置文件的两种方式
    了解过spring-Boot这个技术的,应该知道Spring-Boot的核心配置文件application.properties,当然也可以通过注解自定义配置文件的信息。Spring-Boot读取配置文件的方式:一.读取核心配置文件信息ap...
    99+
    2023-05-31
    spring boot config
  • QT中怎么读写ini配置文件
    这篇文章主要介绍“QT中怎么读写ini配置文件”,在日常操作中,相信很多人在QT中怎么读写ini配置文件问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”QT中怎么读写ini配置文件”的疑惑有所帮助!接下来,请跟...
    99+
    2023-06-21
  • QT中如何读写ini配置文件
    如图1所示,我们需要在QT界面中实现手动读取参数存放的位置,那么我们该如何做呢? 方法:读取ini格式的配置文件,实现路径的写入与读取。 第一步:界面构造函数中,初始化一个Conf...
    99+
    2024-04-02
  • C#读写文本文件(.txt)的方法实例
    读取txt文件 如果你要读取的文件内容不是很多,可以使用 File.ReadAllText(filePath) 或指定编码方式 File.ReadAllText(FilePath...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作