当前位置:网站首页>.NET程序配置文件操作(ini,cfg,config)
.NET程序配置文件操作(ini,cfg,config)
2022-07-03 06:03:00 【xuhss_com】
优质资源分享
| 学习路线指引(点击解锁) | 知识定位 | 人群定位 |
|---|---|---|
| 🧡 Python实战微信订餐小程序 🧡 | 进阶级 | 本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统。 |
| Python量化交易实战 | 入门级 | 手把手带你打造一个易扩展、更安全、效率更高的量化交易系统 |
在程序开发过程中,我们一般会用到配置文件来设定一些参数。常见的配置文件格式为 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>
<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 格式的数据:
///
/// NameValueCollection
///
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>
<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>
///
/// Dictionary
///
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>
<section name="SingleTagConfigNode" type="System.Configuration.SingleTagSectionHandler" />
configSections>
<SingleTagConfigNode PropertyOne="1" PropertyTwo="2" PropertyThree="3" PropertyFour="4" PropertyFive="5" />
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
startup>
configuration>
///
/// SingleTag
///
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>
<section name="MyConfigData1" type="ConsoleApplication.ConfigFiles.ConfigFile,ConsoleApplication"/>
configSections>
<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
我的公众号

边栏推荐
- 88. Merge two ordered arrays
- Redis cannot connect remotely.
- BeanDefinitionRegistryPostProcessor
- Jackson: what if there is a lack of property- Jackson: What happens if a property is missing?
- Deep learning, thinking from one dimensional input to multi-dimensional feature input
- 88. 合并两个有序数组
- PHP notes are super detailed!!!
- Redhat7 system root user password cracking
- 1. 两数之和
- [Shangshui Shuo series together] day 10
猜你喜欢

智牛股--03

Apache+php+mysql environment construction is super detailed!!!

Kubernetes notes (II) pod usage notes
![[advanced pointer (1)] | detailed explanation of character pointer, pointer array, array pointer](/img/9e/a4558e8e53c9655cbc1a38e8c0536e.jpg)
[advanced pointer (1)] | detailed explanation of character pointer, pointer array, array pointer

Kubernetes notes (IX) kubernetes application encapsulation and expansion

Oauth2.0 - explanation of simplified mode, password mode and client mode

Multithreading and high concurrency (7) -- from reentrantlock to AQS source code (20000 words, one understanding AQS)
![[trivia of two-dimensional array application] | [simple version] [detailed steps + code]](/img/84/98c1220d0f7bc3a948125ead6ff3d9.jpg)
[trivia of two-dimensional array application] | [simple version] [detailed steps + code]

How does win7 solve the problem that telnet is not an internal or external command
![[teacher Zhao Yuqiang] MySQL flashback](/img/93/75998e28fd309880661ea723dc8de6.jpg)
[teacher Zhao Yuqiang] MySQL flashback
随机推荐
Introduction to redis using Lua script
MySQL startup error: several solutions to the server quit without updating PID file
[teacher Zhao Yuqiang] MySQL flashback
一起上水碩系列】Day 9
Pytorch builds the simplest version of neural network
[teacher Zhao Yuqiang] the most detailed introduction to PostgreSQL architecture in history
Life is a process of continuous learning
Alibaba cloud Alipay sandbox payment
Troubleshooting of 32GB Jetson Orin SOM failure to brush
伯努利分布,二项分布和泊松分布以及最大似然之间的关系(未完成)
Convolution operation in convolution neural network CNN
[written examination question analysis] | | get [sizeof and strlen] [pointer and array] graphic explanation + code analysis
Apt update and apt upgrade commands - what is the difference?
多线程与高并发(7)——从ReentrantLock到AQS源码(两万字大章,一篇理解AQS)
Error 1045 (28000) occurs when Linux logs in MySQL: access denied for user 'root' @ 'localhost' (using password: yes)
从小数据量 MySQL 迁移数据到 TiDB
理解 YOLOV1 第一篇 预测阶段
Ansible firewall firewalld setting
Solve the problem of automatic disconnection of SecureCRT timeout connection
BeanDefinitionRegistryPostProcessor