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"></add>
  <add key="user" value="sa"></add>
  <add key="password" value="sa"></add>
 </appSettings>
</configuration>

对config配置文件的读写类

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 NetUtilityLib
{
  public static class ConfigHelper
  {
    //依据连接串名字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");
    }

    ///<summary>
    ///返回*.exe.config文件中appSettings配置节的value项
    ///</summary>
    ///<param name="strKey"></param>
    ///<returns></returns>
    public static string GetAppConfig(string strKey)
    {
      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");
    }

    // 修改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;
    }
  }
}

测试代码如下:

class Program
  {
    static void Main(string[] args)
    {
      try
      {
        //string file = System.Windows.Forms.Application.ExecutablePath + ".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.1.11");
        string newIP = ConfigHelper.GetAppConfig("ServerIP");
        Console.WriteLine(newIP);

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

以上这篇C#读写config配置文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • c#读写App.config,ConfigurationManager.AppSettings 不生效的解决方法

    我们经常会希望在程序中写入一些配置信息,例如版本号,以及数据库的连接字符串等.你可能知道在WinForm应用程序中可以利用Properties.Settings来进行类似的工作,但这些其实都利用了App.config配置文件. 本文探讨用代码的方式访问 App.config 的方法.关于 App.config 的使用远比上面提到的用途复杂,因此仅讨论最基本的 appSettings 配置节. 一.配置文件概述: 应用程序配置文件是标准的 XML 文件,XML 标记和属性是区分大小写的.它是可以按

  • 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

  • C#读取配置文件的方法汇总

    配置文件 <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="SQLConfiguration" type="ConfigurationDemo.SQLConfiguration,ConfigurationDemo"/> <section name=&

  • C#读写操作app.config中的数据应用介绍

    读语句: 复制代码 代码如下: String str = ConfigurationManager.AppSettings["DemoKey"]; 写语句: 复制代码 代码如下: Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 2 cfa.AppSettings.Settings["DemoKey"].Value = "D

  • 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

  • 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

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

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

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

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

  • Python读写配置文件的方法

    本文实例讲述了Python读写配置文件的方法.分享给大家供大家参考.具体分析如下: python 读写配置文件在实际应用中具有十分强大的功能,在实际的操作中也有相当简捷的操作方案,以下的文章就是对python 读写配置文件的具体方案的介绍,相信对大家学习Python有所帮助. python 读写配置文件ConfigParser模块是python自带的读取配置文件的模块.通过他可以方便的读取配置文件. 这里就来简单介绍一下python 读写配置文件的方法. 配置文件.顾名思议就是存放配置信息的文件

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

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

  • python读写ini配置文件方法实例分析

    本文实例讲述了python读写ini配置文件方法.分享给大家供大家参考.具体实现方法如下: import ConfigParser import os class ReadWriteConfFile: currentDir=os.path.dirname(__file__) filepath=currentDir+os.path.sep+"inetMsgConfigure.ini" @staticmethod def getConfigParser(): cf=ConfigParser

  • C语言读写配置文件的方法

    本文实例讲述了C语言读写配置文件的方法.分享给大家供大家参考.具体如下: CException.h如下: /************************************************************************/ /* make0000@msn.com */ /************************************************************************/ /***********************

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

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

随机推荐