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

边栏推荐
- MySQL带二进制的库表导出导入
- Pytorch builds the simplest version of neural network
- [teacher Zhao Yuqiang] the most detailed introduction to PostgreSQL architecture in history
- [minesweeping of two-dimensional array application] | [simple version] [detailed steps + code]
- [together Shangshui Shuo series] day 7 content +day8
- 70 shell script interview questions and answers
- BeanDefinitionRegistryPostProcessor
- Kubernetes notes (VIII) kubernetes security
- chromedriver对应版本下载
- Leetcode solution - 02 Add Two Numbers
猜你喜欢

项目总结--01(接口的增删改查;多线程的使用)

phpstudy设置项目可以由局域网的其他电脑可以访问

Deep learning, thinking from one dimensional input to multi-dimensional feature input

Strategy pattern: encapsulate changes and respond flexibly to changes in requirements

Maximum likelihood estimation, divergence, cross entropy

Introduction to redis using Lua script

Solve the problem of automatic disconnection of SecureCRT timeout connection

Clickhouse learning notes (2): execution plan, table creation optimization, syntax optimization rules, query optimization, data consistency

Disruptor learning notes: basic use, core concepts and principles
![[escape character] [full of dry goods] super detailed explanation + code illustration!](/img/33/ec5a5e11bfd43f53f2767a9a0f0cc9.jpg)
[escape character] [full of dry goods] super detailed explanation + code illustration!
随机推荐
智牛股--03
PMP笔记记录
CAD插件的安裝和自動加載dll、arx
BeanDefinitionRegistryPostProcessor
Code generator - single table query crud - generator
Btrfs and ext4 - features, strengths and weaknesses
1. 兩數之和
Understand expectations (mean / estimate) and variances
1. 两数之和
Kubernetes notes (VI) kubernetes storage
Solve the problem of automatic disconnection of SecureCRT timeout connection
Crontab command usage
为什么网站打开速度慢?
[teacher Zhao Yuqiang] kubernetes' probe
Method of finding prime number
项目总结--04
pytorch 多分类中的损失函数
Multithreading and high concurrency (7) -- from reentrantlock to AQS source code (20000 words, one understanding AQS)
Redis encountered noauth authentication required
从 Amazon Aurora 迁移数据到 TiDB