.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). 配置文件,对于程序本身来说,就是基础和依据,其本 ...
随机推荐
- 2021牛客暑期多校训练营3 J 思维
传送门 J-Counting Triangles_2021牛客暑期多校训练营3 (nowcoder.com) 题目 Goodeat finds an undirected complete graph ...
- JavaSE前期准备1
历史(建议了解即可) 一.1990年,美国Sun公司的"Stealth计划"(后改名为"Green计划")目标设置在家用电器等小型系统的程序语言,准备应用在电视 ...
- B3log开源博客compose搭建
B3log开源博客搭建 docker 安装 yum install docker-ce-17.12.1.ce docker-compose 安装 curl -L https://github.com/ ...
- Fastjson tomcat-dhcp链
Fastjson tomcat-dbcp链 这条链可直接回显,可以解决fastjson在内网的情况,因为很多实战的时候,fastjson的应用部署在内网,只映射一个端口出来,导致前面学习的jdbcRo ...
- 全栈交叉编译X86完成过程经验分享
1 CMAKE的交叉编译配置 主要是C和C++编译器的配置和SYSROOT的配置. set (CMAKE_SYSTEM_NAME "Linux") set (CMAKE_SYSTE ...
- [Istio是什么?] 还不知道你就out了,一文40分钟快速理解
@ 目录 前言 Istio是什么? 服务网格是什么? 应用场景 为什么使用Istio? 流量管理介绍 istio架构 Envoy Sidecar Istiod 虚拟服务(VirtualService) ...
- FinOps for Kubernetes - 如何拆分 Kubernetes 成本
本文独立博客阅读地址:https://thiscute.world/posts/finops-for-kubernetes/ 目录 云计算成本管控 Kubernetes 成本分析的难点 Kuberne ...
- 现代 CSS 解决方案:CSS 数学函数
在 CSS 中,其实存在各种各样的函数.具体分为: Transform functions Math functions Filter functions Color functions Image ...
- zabbix的web界面访问失败问题排查
现象:用curl访问显示拒绝链接,查看zabbix-server日志也无异常 1.检查防火墙,SElinux是否关闭 2.检查zabbix-server服务是否启动 3.检查80端口是否被占用,比方是 ...
- linux篇-linux数据库mysql的安装
1数据库文件放到opt下面 2赋予权限775 3运行脚本 4运行成功 5数据库操作 密码修改并刷新 权限修改,允许外部设备访问 6工具连接 7附录 1.显示当前数据库服务器中的数据库列表: mysql ...