C#读写Config配置文件案例
作者:農碼一生 发布时间:2022-10-22 20:11:09
标签: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);
}
}
}
}
来源:https://www.cnblogs.com/wml-it/p/14813617.html


猜你喜欢
- 最近有个粉丝提了个问题,说他在Spring Security中用JWT做退出登录的时无法获取当前用户,导致无法证明“我就是要退出的那个我”,
- 本文实例讲述了Android编程使用pull方式解析xml格式文件的方法。分享给大家供大家参考,具体如下:上次已经说过使用Android s
- 本文实例讲述了Android桌面插件App Widget用法。分享给大家供大家参考,具体如下:应用程序窗口小部件App Widgets应用程
- 在idea中安装完ActivateJrebel以后,运行时弹出激活页面,输入团队地址: http://jrebel.whrj999.com/
- 前言Spring JPA是目前比较常用的ORM解决方案,但是其对于某些场景并不是特别的方便,例如查询部分字段,联表查询,子查询等。而接下来我
- 现在网上很多应用都是用二维码来分享网址或者其它的信息。尤其在移动领域,二维码更是有很大的应用场景。因为项目的需要,需要在网站中增加一个生成二
- 前言前面说过了类的加载机制,里面讲到了类的初始化中时用到了一部分内存管理的知识,这里让我们来看下Java虚拟机是如何管理内存的。先让我们来看
- 前言用过Spring的人多多少少也都用过@Async注解,至于作用嘛,看注解名,大概能猜出来,就是在方法执行的时候进行异步执行。一、如何使用
- 本文实例讲述了WinForm通过操作注册表实现限制软件使用次数的方法。分享给大家供大家参考,具体如下:1.创建注册表文件:打开记事本,输入一
- springboot项目main函数启动在controller包下新建appController类package controller;im
- 先介绍一下API,与其他文章不同的是,本文采取类比的方式来讲,同时结合源码。而不像其他文章一样,一个个API罗列出来,让人找不到重点。1、O
- 多段颜色的进度条实现思路,供大家参考,具体内容如下这个进度条其实相对简单. 这里可以把需要绘制的简单分为两个部分1.灰色背景部分 2.多段颜
- 由于众所周知的原因,maven的库在中国大陆非常慢。我在百度上搜到的大部分文章都是直接在~/.m2/settings.xml 加入以下内容&
- 目录1、成员2、辅助功能3、字段4、方法4.1参数4.2方法主体和局部变量4.3静态和实例方法4.4虚方法、重写方法和抽象方法4.5方法重载
- EntityWrapper使用解析1、项目中引入jar包,我这里使用Maven构建<dependency> &nbs
- C# FileStream类在 C# 语言中文件读写流使用 FileStream 类来表示,FileStream 类主要用于文件的读写,不仅
- Spring简介和配置学习目标【应用】能够独立完成springIOC的快速入门【应用】能够掌握spring的bean标签的配置【应用】能够独
- 说明:1、集合类型参数化;2、可根据集合中的对象的各个属性进行排序,传入属性名称即可;注:属性必须实现了IComparable接口,C#中i
- 实现原理: 长连接的维持,是要客户端程序,定时向服务端程序,发送一个
- 前言在分布式场景下为了保证数据最终一致性。在单进程的系统中,存在多个线程可以同时改变某个变量(可变共享变量)时,就需要对变量或代码块做同步(