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

博客 动态
0 165
优雅殿下
优雅殿下 2022-06-29 14:01:09
悬赏:0 积分 收藏

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

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

在程序开发过程中,我们一般会用到配置文件来设定一些参数。常见的配置文件格式为 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>		        <!--以NameValueCollection键值对的形式返回配置节点中的信息,type值固定为System.Configuration.NameValueSectionHandler-->		            <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 格式的数据:

/// <summary>/// NameValueCollection/// </summary>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>		<!--以Dictionary字典的形式返回配置节点中的信息,type固定为System.Configuration.DictionarySectionHandler-->		<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>
/// <summary>/// Dictionary/// </summary>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>		<!--基础结构处理 .config 文件中由单个 XML 标记所表示的各配置节点中的值,type固定为System.Configuration.SingleTagSectionHandler-->		<section name="SingleTagConfigNode" type="System.Configuration.SingleTagSectionHandler" />	</configSections>	<!--自定义配置节点-->	<!--注意,只能是单个节SingleTagSectionHandler才能处理,无论有多少个属性都能处理-->	<SingleTagConfigNode PropertyOne="1" PropertyTwo="2" PropertyThree="3" PropertyFour="4" PropertyFive="5" />    <startup>         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />    </startup></configuration>
/// <summary>/// SingleTag/// </summary>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>		<!--把MyConfigData1节点的数据映射到MyConfigData类中-->		<section name="MyConfigData1" type="ConsoleApplication.ConfigFiles.ConfigFile,ConsoleApplication"/>	</configSections>	<!--自定义配置节点,configSource指定自定义配置文件的路径(必须是相对路径)-->	<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

我的公众号

posted @ 2022-06-29 13:42 wang2009 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    优雅殿下

    优雅殿下 (王者 段位)

    2018 积分 (2)粉丝 (47)源码

    小小码农,大大世界

     

    温馨提示

    亦奇源码

    最新会员