.NET程序配置文件操作(ini,cfg,config)
在程序开发过程中,我们一般会用到配置文件来设定一些参数。常见的配置文件格式为 ini, xml, config等。
INI
.ini文件,通常为初始化文件,是用来存储程序配置信息的文本文件。
[Login]
#开启加密 0:不开启、1:开启
open_ssl_certificate=0
.NET 框架本身不支持 INI 文件,可以利用 Windows API方法使用平台调用服务来写入和读取文件。
// 要写入的部分名称 - sectionName
// 要设置的键名 - key
// 要设置的值 - value
// INI文件位置 - filepath
// 读取是否成功 - result
[DllImport("kernel32")]
bool WritePrivateProfileString(string sectionName,string key,string value,string filepath);
// 要读取的部分名称 - sectionName
// 要读取的键名 - key
// 如果键不存在返回的默认值 - default
// 接收用作缓冲区的字符串 - ReturnedVal
// 实际读取的值 - maxsize
// INI文件位置 - filepath
[DllImport("kernel32")]
int GetPrivateProfileString(string sectionName,string key,string default,StringBuilder ReturnedVal,int maxsize,string filepath);
一般会封装一个类来调用该API方法。
public class ReadWriteINIFile{
...
public void WriteINI(string name, string key, string value)
{
WritePrivateProfileString(name, key, value, _path);
}
public string ReadINI(string name, string key)
{
StringBuilder sb = new StringBuilder(255);
int ini = GetPrivateProfileString(name, key, "", sb, 255, _path);
return sb.ToString();
}
}
CFG
SharpConfig 是 .NET 的CFG/INI 配置文件操作组件,以文本或二进制格式读取,修改和保存配置文件和流。
Configuration config = Configuration.LoadFromFile("login.cfg");
Section section = config["Login"];
// 读取参数
bool isOpen = section["open_ssl_certificate"].GetValue<bool>();
// 修改参数
section["open_ssl_certificate"].Value = false;
Config
在 App.config/web.config 文件中的 configSections 节点下配置 section 节点,.NET 提供自带的类型进行封装。
configSections节点必须为configuration下第一个节点。
NameValue键值对
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!--以NameValueCollection键值对的形式返回配置节点中的信息,type值固定为System.Configuration.NameValueSectionHandler-->
<section name="NameValueConfigNode" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<!--自定义配置节点-->
<NameValueConfigNode>
<add key="Name一" value="Value一" />
<add key="Name二" value="Value二" />
</NameValueConfigNode>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>
定义一个静态属性的方法获取 Dictionary 格式的数据:
/// <summary>
/// NameValueCollection
/// </summary>
public static Dictionary<string, string> NameValueConfigNode
{
get
{
NameValueCollection nvc = (NameValueCollection)ConfigurationManager.GetSection("NameValueConfigNode");
Dictionary<string, string> result = new Dictionary<string,string>();
foreach (string key in nvc.AllKeys)
{
result.Add(key, nvc[key]);
}
return result;
}
}
Dictionary
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!--以Dictionary字典的形式返回配置节点中的信息,type固定为System.Configuration.DictionarySectionHandler-->
<section name="DictionaryConfigNode" type="System.Configuration.DictionarySectionHandler"/>
</configSections>
<!--自定义配置节点-->
<DictionaryConfigNode>
<add key="Key一" value="DictValue一" />
<add key="Key二" value="DictValue二" />
</DictionaryConfigNode>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>
/// <summary>
/// Dictionary
/// </summary>
public static Dictionary<string, string> DictionaryConfigNode
{
get
{
IDictionary dict = (IDictionary)ConfigurationManager.GetSection("DictionaryConfigNode");
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (string key in dict.Keys)
{
result.Add(key, dict[key].ToString());
}
return result;
}
}
SingTag
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!--基础结构处理 .config 文件中由单个 XML 标记所表示的各配置节点中的值,type固定为System.Configuration.SingleTagSectionHandler-->
<section name="SingleTagConfigNode" type="System.Configuration.SingleTagSectionHandler" />
</configSections>
<!--自定义配置节点-->
<!--注意,只能是单个节SingleTagSectionHandler才能处理,无论有多少个属性都能处理-->
<SingleTagConfigNode PropertyOne="1" PropertyTwo="2" PropertyThree="3" PropertyFour="4" PropertyFive="5" />
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>
/// <summary>
/// SingleTag
/// </summary>
public static Dictionary<string, string> SingleTagConfigNode
{
get
{
Hashtable dict = (Hashtable)ConfigurationManager.GetSection("SingleTagConfigNode");
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (string key in dict.Keys)
{
result.Add(key, dict[key].ToString());
}
return result;
}
}
自定义配置文件
如果配置文件很多,可以单独定义配置文件,然后在 App.config/Web.config 文件中声明。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!--把MyConfigData1节点的数据映射到MyConfigData类中-->
<section name="MyConfigData1" type="ConsoleApplication.ConfigFiles.ConfigFile,ConsoleApplication"/>
</configSections>
<!--自定义配置节点,configSource指定自定义配置文件的路径(必须是相对路径)-->
<MyConfigData configSource="ConfigFiles\MyConfigFile.config"/>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>
自定义文件 MyConfigFile.config 内容:
<?xml version="1.0" encoding="utf-8" ?>
<MyConfigData>
<add key="Key一" value="自定义文件一" />
<add key="Key二" value="自定义文件二" />
<add key="Key三" value="自定义文件三" />
</MyConfigData>
XML
XML文件常用于简化数据的存储和共享,它的设计宗旨是传输数据,而非显示数据。对于复杂不规则的配置信息也可以用XML文件进行存储。
// 读取文件
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("myfile.xml");
// 根节点
var nodeRoot = xmlDoc.DocumentElement;
// 创建新节点
XmlElement studentNode = xmlDoc.CreateElement("student");
// 创建新节点的孩子节点
XmlElement nameNode = xmlDoc.CreateElement("name");
// 建立父子关系
studentNode.AppendChild(nameNode);
nodeRoot.AppendChild(studentNode);
XML基础教程:https://www.w3school.com.cn/xml/index.asp
我的公众号

.NET程序配置文件操作(ini,cfg,config)的更多相关文章
- C# 应用程序配置文件操作
应用程序配置文件,对于asp.net是 web.config对于WINFORM程序是 App.Config(ExeName.exe.config). 配置文件,对于程序本身来说,就是基础和依据,其本质 ...
- Config程序配置文件操作实践进阶之ConfigurationSectionGroup
今天又进一步对System.Configuration下的ConfigurationSectionGroup类及相关的类与方法进行了研究.发现要构建多层次嵌套的XML标签 则必须用到Configura ...
- 配置文件操作(ini、cfg、xml、config等格式)
配置文件的格式主要有ini.xml.config等,现在对这些格式的配置文件的操作(C#)进行简单说明. INI配置文件操作 调用系统函数GetPrivateProfileString()和Write ...
- Config程序配置文件(configSections)操作实践及代码详注
所有与配置文件相关的类:(粗体为一般情况下使用到的类,其它类功能可能在很复杂的情况下才使用到.) 1.ConfigurationManager,这个提供用于打开客户端应用程序集的Configurati ...
- C#----操作应用程序配置文件App.config
对配置文件的一些疑问: 在应用程序的目录下,有两处值得注意的地方,一个是应用程序根目录下的App.config文件,和bin\debug\name.exe.config 或者 bin\Release\ ...
- C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作
原文 http://www.cnblogs.com/codealone/archive/2013/09/22/3332607.html 应用程序配置文件,对于asp.net是 web.config,对 ...
- C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作,无法为请求的 Configuration 对象创建配置文件。
应用程序配置文件,对于asp.net是 web.config,对于WINFORM程序是 App.Config(ExeName.exe.config). 配置文件,对于程序本身来说,就是基础和依据,其本 ...
- 【个人使用.Net类库】(1)INI配置文件操作类
开发接口程序时,对于接口程序配置的IP地址.端口等都需要是可配置的,而在Win Api原生实现了INI文件的读写操作,因此只需要调用Win Api中的方法即可操作INI配置文件,关键代码就是如何调用W ...
- C# 应用程序配置文件App.Config和web.config
应用程序配置文件,对于asp.net是 web.config,对于WINFORM程序是 App.Config(ExeName.exe.config). 配置文件,对于程序本身来说,就是基础和依据,其本 ...
随机推荐
- Metalama简介2.利用Aspect在编译时进行消除重复代码
上文介绍到Aspect是Metalama的核心概念,它本质上是一个编译时的AOP切片.下面我们就来系统说明一下Metalama中的Aspect. Metalama简介1. 不止是一个.NET跨平台的编 ...
- Java语言学习day38--8月13日
###11哈希表的数据结构 A:哈希表的数据结构:(参见图解) 加载因子:表中填入的记录数/哈希表的长度 例如: 加载因子是0.75 代表: 数组中的16个位置,其中存入16*0.75=12个元素 如 ...
- 2021.07.02 UVa1197 多路归并模板
2021.07.02 UVa1197 多路归并模板 UVA11997 K Smallest Sums - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 分析: 题解 UVA11997 ...
- JavaWeb和WebGIS学习笔记(四)——使用uDig美化地图,并叠加显示多个图层
系列链接: Java web与web gis学习笔记(一)--Tomcat环境搭建 Java web与web gis学习笔记(二)--百度地图API调用 JavaWeb和WebGIS学习笔记(三)-- ...
- linux下的redis操作
安装 .启动.连接 下载包:wget http://download.redis.io/releases/redis-4.0.8.tar.gz 解压 :tar -xzf redis-4.0.8.ta ...
- 解决vue安装less报错Failed to compile with 1 errors的问题
1.创建vue项目后安装less,执行 npm install less less-loader --save-dev 下载版本为:less-loader@6.1.0 , less@3.11.3,重启 ...
- golang get process name by pid
一个很好的问题:How golang to get process name by process id (pid)? 目前看来go api并没有提供通过pid获取进程名称的方法,可以通过 /proc ...
- OpenStack计费服务
cloudkitty服务介绍 当前版本cloudkitty可以完成虚拟机实例(compute),云硬盘(volume),镜像(image),网络进出流量(network.bw.in,network.b ...
- 【mq】从零开始实现 mq-09-消费者拉取消息 pull message
前景回顾 [mq]从零开始实现 mq-01-生产者.消费者启动 [mq]从零开始实现 mq-02-如何实现生产者调用消费者? [mq]从零开始实现 mq-03-引入 broker 中间人 [mq]从零 ...
- css,html实现元素超出部分省略号
.line-1 { height: 25px; width: 200px; overflow: hidden; text-overflow: ellipsis; display: -webkit-bo ...