C#读取INI文件

       虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。

       INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value)

[Section]

Key=Value

       VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面是一个C# ini文件读写类,从网上收集的,很全,就是没有对section的改名功能,高手可以增加一个。

  1 using System;
  2 using System.IO;
  3 using System.Runtime.InteropServices;
  4 using System.Text;
  5 using System.Collections;
  6 using System.Collections.Specialized;
  7  
  8 namespace wuyisky
  9 {
 10     /// <summary>
 11     /// IniFiles的类
 12     /// </summary>
 13     public class IniFiles
 14     {
 15         public string FileName; //INI文件名
 16         //声明读写INI文件的API函数
 17         [DllImport("kernel32")]
 18         private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
 19         [DllImport("kernel32")]
 20         private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
 21         //类的构造函数,传递INI文件名
 22         public IniFiles(string AFileName)
 23         {
 24             // 判断文件是否存在
 25             FileInfo fileInfo = new FileInfo(AFileName);
 26             //Todo:搞清枚举的用法
 27             if ((!fileInfo.Exists))
 28             { //|| (FileAttributes.Directory in fileInfo.Attributes))
 29                 //文件不存在,建立文件
 30                 System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default);
 31                 try
 32                 {
 33                     sw.Write("#表格配置档案");
 34                     sw.Close();
 35                 }
 36                 catch
 37                 {
 38                     throw (new ApplicationException("Ini文件不存在"));
 39                 }
 40             }
 41             //必须是完全路径,不能是相对路径
 42             FileName = fileInfo.FullName;
 43         }
 44         //写INI文件
 45         public void WriteString(string Section, string Ident, string Value)
 46         {
 47             if (!WritePrivateProfileString(Section, Ident, Value, FileName))
 48             {
 49                 throw (new ApplicationException("写Ini文件出错"));
 50             }
 51         }
 52         //读取INI文件指定
 53         public string ReadString(string Section, string Ident, string Default)
 54         {
 55             Byte[] Buffer = new Byte[65535];
 56             int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName);
 57             //必须设定0(系统默认的代码页)的编码方式,否则无法支持中文
 58             string s = Encoding.GetEncoding(0).GetString(Buffer);
 59             s = s.Substring(0, bufLen);
 60             return s.Trim();
 61         }
 62  
 63         //读整数
 64         public int ReadInteger(string Section, string Ident, int Default)
 65         {
 66             string intStr = ReadString(Section, Ident, Convert.ToString(Default));
 67             try
 68             {
 69                 return Convert.ToInt32(intStr);
 70             }
 71             catch (Exception ex)
 72             {
 73                 Console.WriteLine(ex.Message);
 74                 return Default;
 75             }
 76         }
 77  
 78         //写整数
 79         public void WriteInteger(string Section, string Ident, int Value)
 80         {
 81             WriteString(Section, Ident, Value.ToString());
 82         }
 83  
 84         //读布尔
 85         public bool ReadBool(string Section, string Ident, bool Default)
 86         {
 87             try
 88             {
 89                 return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));
 90             }
 91             catch (Exception ex)
 92             {
 93                 Console.WriteLine(ex.Message);
 94                 return Default;
 95             }
 96         }
 97  
 98         //写Bool
 99         public void WriteBool(string Section, string Ident, bool Value)
100         {
101             WriteString(Section, Ident, Convert.ToString(Value));
102         }
103  
104         //从Ini文件中,将指定的Section名称中的所有Ident添加到列表中
105         public void ReadSection(string Section, StringCollection Idents)
106         {
107             Byte[] Buffer = new Byte[16384];
108             //Idents.Clear();
109  
110             int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(0),
111                   FileName);
112             //对Section进行解析
113             GetStringsFromBuffer(Buffer, bufLen, Idents);
114         }
115  
116         private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)
117         {
118             Strings.Clear();
119             if (bufLen != 0)
120             {
121                 int start = 0;
122                 for (int i = 0; i < bufLen; i++)
123                 {
124                     if ((Buffer[i] == 0) && ((i - start) > 0))
125                     {
126                         String s = Encoding.GetEncoding(0).GetString(Buffer, start, i - start);
127                         Strings.Add(s);
128                         start = i + 1;
129                     }
130                 }
131             }
132         }
133         //从Ini文件中,读取所有的Sections的名称
134         public void ReadSections(StringCollection SectionList)
135         {
136             //Note:必须得用Bytes来实现,StringBuilder只能取到第一个Section
137             byte[] Buffer = new byte[65535];
138             int bufLen = 0;
139             bufLen = GetPrivateProfileString(null, null, null, Buffer,
140              Buffer.GetUpperBound(0), FileName);
141             GetStringsFromBuffer(Buffer, bufLen, SectionList);
142         }
143         //读取指定的Section的所有Value到列表中
144         public void ReadSectionValues(string Section, NameValueCollection Values)
145         {
146             StringCollection KeyList = new StringCollection();
147             ReadSection(Section, KeyList);
148             Values.Clear();
149             foreach (string key in KeyList)
150             {
151                 Values.Add(key, ReadString(Section, key, ""));
152             }
153         }
154         ////读取指定的Section的所有Value到列表中,
155         //public void ReadSectionValues(string Section, NameValueCollection Values,char splitString)
156         //{  string sectionValue;
157         //  string[] sectionValueSplit;
158         //  StringCollection KeyList = new StringCollection();
159         //  ReadSection(Section, KeyList);
160         //  Values.Clear();
161         //  foreach (string key in KeyList)
162         //  {
163         //    sectionValue=ReadString(Section, key, "");
164         //    sectionValueSplit=sectionValue.Split(splitString);
165         //    Values.Add(key, sectionValueSplit[0].ToString(),sectionValueSplit[1].ToString());
166  
167         //  }
168         //}
169         //清除某个Section
170         public void EraseSection(string Section)
171         {
172             if (!WritePrivateProfileString(Section, null, null, FileName))
173             {
174                 throw (new ApplicationException("无法清除Ini文件中的Section"));
175             }
176         }
177         //删除某个Section下的键
178         public void DeleteKey(string Section, string Ident)
179         {
180             WritePrivateProfileString(Section, Ident, null, FileName);
181         }
182         //Note:对于Win9X,来说需要实现UpdateFile方法将缓冲中的数据写入文件
183         //在Win NT, 2000和XP上,都是直接写文件,没有缓冲,所以,无须实现UpdateFile
184         //执行完对Ini文件的修改之后,应该调用本方法更新缓冲区。
185         public void UpdateFile()
186         {
187             WritePrivateProfileString(null, null, null, FileName);
188         }
189  
190         //检查某个Section下的某个键值是否存在
191         public bool ValueExists(string Section, string Ident)
192         {
193             StringCollection Idents = new StringCollection();
194             ReadSection(Section, Idents);
195             return Idents.IndexOf(Ident) > -1;
196         }
197  
198         //确保资源的释放
199         ~IniFiles()
200         {
201             UpdateFile();
202         }
203     }
204 }
View Code

 

文章来源:http://www.cnblogs.com/nozer/articles/1934958.html

 

转载于:https://www.cnblogs.com/qiernonstop/p/4250619.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/298162.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

本地打开extjs api docs 的方法

将docs目录下 index.html 中的 <script type"text/javascript"src"../adapter/ext/ext-base.js">替换为 <script type"text/javascript"src"../adapter/jquery/jquery-1.4.2.min.js"></script><script type&quo…

独孤思维:穷b只对小概率惶恐不安,对100%确定却视而不见

穷b只对小概率事件惶恐不安&#xff0c;而对于100%确定的事情却视而不见。 穷逼有一个特点&#xff0c;喜欢把外界问题当作自己最大的挡箭牌&#xff1a; 对于小概率发生的事件&#xff0c;惶恐不安&#xff0c;避而远之&#xff0c;而对于100%确定的事情&#xff0c;却装作视…

电子报账系统源码_亲清直播间 | “互联网+财税”引领企业专票电子化变革

2019年11月27日&#xff0c;国务院常务会议要求“ 2020年年底前实现增值税专用发票电子化”&#xff0c;这标志着将增值税专用发票电子化工作正式提上日程。2020年8月3日&#xff0c;国家税务总局发布《关于进一步支持和服务长江三角洲区域一体化发展若干措施的通知》(税总函〔…

Dapr牵手.NET学习笔记:想入非非的服务调用

demo运行环境&#xff1a;Windows10&#xff0c;Docker(dapr_zipkin&#xff0c;dapr_redid&#xff0c;dapr_placement)安装&#xff1a;dapr init卸载&#xff1a;dapr uninstall&#xff0c;然后删除 C:\Users\当前用户\.daprdapr在部署时是通过给服务挂载一个sidecar&#…

老婆晚上不想睡?这个操作你要会!

1 会跪键盘吗&#xff1f;2 吃鸡时捡装备的你3 这是个失败之作4 是时候让你见识什么叫真正的技术了 5 别人的老师 6 陷入僵橘7 恐高者慎看你点的每个赞&#xff0c;我都认真当成了喜欢

java中JOptionPane类_java:JOptionPane类消息框总结

最近在写projet时经常用到JOptionPane的消息提示框&#xff0c;今天在这里做一个总结。主要用到四种消息提示框方法&#xff1a;showMessageDialog()&#xff1a;消息对话框showOptionDialog()&#xff1a;选择对话框showInputDialog()&#xff1a;输入对话框showConfirmDialog…

ACPI知识学习笔记

ACPI table之FACP(Fixed ACPI Description Table). 在代码里面&#xff1a;Resources\AcpiTables\Fadt\Fadt3.0.act 定义了EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE Fadt. 列举出比较重要且常用的几项&#xff1a; INT_MODEL, //System Interrupt ModelSCI_INT_VEC…

Linux实战考试题:批量创建用户和密码-看看你会么?

批量创建10个用户stu01-stu10&#xff0c;并且设置随机8位密码&#xff0c;要求&#xff1a;不能用shell循环&#xff08;例如&#xff1a;for,while等&#xff09;&#xff0c;只能用linux命令及管道实现。此题考察的是基础命令的熟练运用&#xff0c;因此&#xff0c;限制了使…

python继承方式是基于原型吗_基于原型与基于类的继承

小编典典这里大约有一百个术语问题&#xff0c;大多数是围绕某人(不是您)试图使他们的想法听起来像是“最好的”。所有面向对象的语言都必​​须能够处理以下几个概念&#xff1a;数据封装以及对数据的关联操作&#xff0c;除其他外&#xff0c;各种操作被称为数据成员和成员函…

【视频】CCNA——telnet和SSH的配置

链接失效请E-MAIL&#xff1a;loguis-iehotmail.com地址&#xff1a;http://u.115.com/file/f4e6e095f3转载于:https://blog.51cto.com/loguis/332652

每天扫扫扫,二维码会被我们扫完吗?

全世界只有3.14 % 的人关注了爆炸吧知识支付码、名片码、健康码、校园码、复学码、乘车码、挪车码码码码码码码码码码码码码码码码码码码码码码码码码码&#xff0c;这么多码&#xff1f;光疫情期间&#xff0c;就用掉了 1400亿个二维码&#xff0c;那么就有同学来问了&#xf…

高级SQL注入拿shell,一般黑客不知道。哈客

服务器只有一个站,又找不到注入点怎么办? 你可以试试在搜索框,登陆,任何框框里放个单引号,看看是否报错 初级部分 加个单引号,后面随便,随便填个密码,点击登陆 典型的SQL注入判断权限: and user>0-- 明显的sa权限获取数据库名字: and db_name()>0-- 很…

使用 SVG 动画实现弹性的页面元素效果

Codrops 分享了一些给SVG元素加上弹性动画的灵感。实现的思路是把一个SVG元素整合成一个组件&#xff0c;然后从一个路径弹性动画到另一个。这种效果可以应用到像菜单&#xff0c;按钮或其它元素&#xff0c;使得交互更有趣&#xff0c;看起更原生与自然的感觉。 在线演示 …

CCNA,CCNP资料

CCNA资料、、、、、、、、、、、、、、、、、、、、转载于:https://blog.51cto.com/youye/334779

虚拟ip工具_针对游戏防封换IP有用吗?

如今的网游有的有局限ip地址登录&#xff0c;就是说1个ip地址只可以登录1个或是两个客户端&#xff0c;可是也不是全部的游戏都局限&#xff0c;那麼针对ip限制怎样游戏多开呢&#xff1f;游戏局限针对许多用户而言是很不太好的&#xff0c;由于它们需用非常好号来挂&#xff0…

万万没想到,刷1000道题目,还不如搞懂这几个机械动图!

▲ 点击查看 著名教育家蒙台梭利曾说&#xff1a;“孩子成长中最重要、最基本的就是注意力集中”。而乔布斯也曾说&#xff1a;“专注和简单一直是我的秘诀之一。观察一下你家的孩子&#xff0c;会不会经常出现这种情况:孩子上课坐不住、总跑神&#xff0c;小动作不断&#xf…

Mysql日期

2019独角兽企业重金招聘Python工程师标准>>> create view fin1 as select o.code, s.organization_name,s.name,s.sex,s.identity_card_number,date_format(s.final_into_association_time,%Y-%m-%d),s.number_of_worked_in_association,(year(now())-year(s.begin_…

复制一个文件夹中的所有文件和文件夹的java程序实现

使用java程序实现了对文件夹的复制功能&#xff1a; package demo.io; import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import j…

Silverlight 2.5D RPG游戏技巧与特效处理:(十六)动态资源

即开即玩是网页游戏相比传统客户端游戏的最大优势。如果说在每台电脑安装上G的客户端是一种资源浪费及时间污染&#xff1b;那么Silverlight作为RIA界的新宠儿&#xff0c;在继承祖辈优秀血统的前提下拥有更加卓越的性能及更为曼妙的动态表现&#xff0c;势将引领网络未来世界进…

python pp模块_Python模块--Pexpect

探索 Pexpect&#xff0c;第 1 部分&#xff1a;剖析 Pexpect概述Pexpect 是 Don Libes 的 Expect 语言的一个 Python 实现&#xff0c;是一个用来启动子程序&#xff0c;并使用正则表达式对程序输出做出特定响应&#xff0c;以此实现与其自动交互的 Python 模块。 Pexpect 的使…