当前位置:网站首页>.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
我的公众号

边栏推荐
- Detailed explanation of iptables (1): iptables concept
- [Zhao Yuqiang] deploy kubernetes cluster with binary package
- Redhat7 system root user password cracking
- Pytorch builds the simplest version of neural network
- phpstudy设置项目可以由局域网的其他电脑可以访问
- Error 1045 (28000) occurs when Linux logs in MySQL: access denied for user 'root' @ 'localhost' (using password: yes)
- Life is a process of continuous learning
- 从小数据量分库分表 MySQL 合并迁移数据到 TiDB
- CAD插件的安装和自动加载dll、arx
- Convolution operation in convolution neural network CNN
猜你喜欢

Jedis source code analysis (I): jedis introduction, jedis module source code analysis
![[teacher Zhao Yuqiang] calculate aggregation using MapReduce in mongodb](/img/cc/5509b62756dddc6e5d4facbc6a7c5f.jpg)
[teacher Zhao Yuqiang] calculate aggregation using MapReduce in mongodb

伯努利分布,二项分布和泊松分布以及最大似然之间的关系(未完成)

Jedis source code analysis (II): jediscluster module source code analysis

Skywalking8.7 source code analysis (II): Custom agent, service loading, witness component version identification, transform workflow

Kubernetes notes (VI) kubernetes storage

智牛股项目--04

Today, many CTOs were killed because they didn't achieve business

Convolution operation in convolution neural network CNN

Apt update and apt upgrade commands - what is the difference?
随机推荐
GPS坐标转百度地图坐标的方法
Strategy pattern: encapsulate changes and respond flexibly to changes in requirements
Solve the problem that Anaconda environment cannot be accessed in PowerShell
1. Sum of two numbers
Bio, NiO, AIO details
Synthetic keyword and NBAC mechanism
Simple solution of small up main lottery in station B
Skywalking8.7 source code analysis (I): agent startup process, agent configuration loading process, custom class loader agentclassloader, plug-in definition system, plug-in loading
[branch and cycle] | | super long detailed explanation + code analysis + a trick game
从小数据量分库分表 MySQL 合并迁移数据到 TiDB
最大似然估计,散度,交叉熵
Oauth2.0 - Introduction and use and explanation of authorization code mode
What's the difference between using the Service Worker Cache API and regular browser cache?
Personal outlook | looking forward to the future from Xiaobai's self analysis and future planning
Why is the website slow to open?
Error 1045 (28000) occurs when Linux logs in MySQL: access denied for user 'root' @ 'localhost' (using password: yes)
Skywalking8.7 source code analysis (II): Custom agent, service loading, witness component version identification, transform workflow
[teacher Zhao Yuqiang] kubernetes' probe
The most responsible command line beautification tutorial
Pytorch dataloader implements minibatch (incomplete)