当前位置:网站首页>.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
我的公众号
边栏推荐
- Solve the problem that Anaconda environment cannot be accessed in PowerShell
- tabbar的设置
- [teacher Zhao Yuqiang] use Oracle's tracking file
- Alibaba cloud OOS file upload
- 88. 合并两个有序数组
- Kubernetes notes (10) kubernetes Monitoring & debugging
- [advanced pointer (2)] | [function pointer, function pointer array, callback function] key analysis + code explanation
- Analysis of Clickhouse mergetree principle
- It is said that the operation and maintenance of shell scripts are paid tens of thousands of yuan a month!!!
- Common exceptions when Jenkins is released (continuous update...)
猜你喜欢
pytorch DataLoader实现miniBatch(未完成)
Kubernetes notes (IX) kubernetes application encapsulation and expansion
[branch and cycle] | | super long detailed explanation + code analysis + a trick game
[teacher Zhao Yuqiang] index in mongodb (Part 2)
伯努利分布,二项分布和泊松分布以及最大似然之间的关系(未完成)
Why is the website slow to open?
Alibaba cloud OOS file upload
Kubernetes notes (III) controller
Error 1045 (28000) occurs when Linux logs in MySQL: access denied for user 'root' @ 'localhost' (using password: yes)
Detailed explanation of contextclassloader
随机推荐
Introduction to redis using Lua script
[teacher Zhao Yuqiang] Flink's dataset operator
[teacher Zhao Yuqiang] MySQL high availability architecture: MHA
1. 两数之和
Es 2022 officially released! What are the new features?
[video of Teacher Zhao Yuqiang's speech on wot] redis high performance cache and persistence
Loss function in pytorch multi classification
智牛股--03
[advanced pointer (1)] | detailed explanation of character pointer, pointer array, array pointer
[together Shangshui Shuo series] day 7 content +day8
理解 期望(均值/估计值)和方差
Oauth2.0 - explanation of simplified mode, password mode and client mode
Kubernetes cluster environment construction & Deployment dashboard
[Shangshui Shuo series together] day 10
项目总结--01(接口的增删改查;多线程的使用)
CAD插件的安裝和自動加載dll、arx
Niuke JS separator
Ansible firewall firewalld setting
[teacher Zhao Yuqiang] index in mongodb (Part 2)
从 Amazon Aurora 迁移数据到 TiDB