• .NET程序配置文件操作(ini,cfg,config)


    🚀 优质资源分享 🚀

    学习路线指引(点击解锁)知识定位人群定位
    🧡 Python实战微信订餐小程序 🧡进阶级本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统。
    💛Python量化交易实战💛入门级手把手带你打造一个易扩展、更安全、效率更高的量化交易系统

    在程序开发过程中,我们一般会用到配置文件来设定一些参数。常见的配置文件格式为 ini, xml, config等。

    INI

    .ini文件,通常为初始化文件,是用来存储程序配置信息的文本文件。

    [Login]
    #开启加密 0:不开启、1:开启
    open\_ssl\_certificate=0
    
    
    • 1
    • 2
    • 3
    • 4

    .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);
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    一般会封装一个类来调用该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();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    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;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    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>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    定义一个静态属性的方法获取 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;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    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>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    /// 
    /// 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;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    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>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    /// 
    /// 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;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    自定义配置文件

    如果配置文件很多,可以单独定义配置文件,然后在 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>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    自定义文件 MyConfigFile.config 内容:

    xml version="1.0" encoding="utf-8" ?
    <MyConfigData>
    	<add key="Key一" value="自定义文件一" />
    	<add key="Key二" value="自定义文件二" />
    	<add key="Key三" value="自定义文件三" />
    MyConfigData>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    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);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    XML基础教程:https://www.w3school.com.cn/xml/index.asp

    我的公众号

  • 相关阅读:
    b2b.ccb.com:443 需要你的凭据
    pod&node选择部署策略: nodeSelector和nodeAffinity
    ASM字节码操作类库(打开java语言世界通往字节码世界的大门) | 京东云技术团队
    rabbitmq-3.8.15集群、集群镜像模式安装部署
    【生活】罗曼·罗兰语录
    Linux系统导入导出docker容器的sql数据
    OpenCV 人脸检测(易上手版)
    软件测试|Python自动化测试实现的思路
    【Note】二叉树的遍历
    python数据管理和分析
  • 原文地址:https://blog.csdn.net/xuhss_com/article/details/125532447