C#读取ini文件的方法
最近项目用到ini文件,读取ini文件,方法如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms; namespace test{
/// <summary>
/// IniFiles的类
/// </summary>
public class IniFiles
{
public string FileName; //INI文件名
//string path = System.IO.Path.Combine(Application.StartupPath,"pos.ini"); //声明读写INI文件的API函数
[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath); //类的构造函数,传递INI文件名
public IniFiles(string AFileName)
{
// 判断文件是否存在
FileInfo fileInfo = new FileInfo(AFileName);
//Todo:搞清枚举的用法
if ((!fileInfo.Exists))
{ //|| (FileAttributes.Directory in fileInfo.Attributes))
//文件不存在,建立文件
System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default);
try
{
sw.Write("#表格配置档案");
sw.Close();
}
catch
{
throw (new ApplicationException("Ini文件不存在"));
}
}
//必须是完全路径,不能是相对路径
FileName = fileInfo.FullName;
} //写INI文件
public void WriteString(string Section, string Ident, string Value)
{
if (!WritePrivateProfileString(Section, Ident, Value, FileName))
{ throw (new ApplicationException("写Ini文件出错"));
}
} //读取INI文件指定
public string ReadString(string Section, string Ident, string Default)
{
Byte[] Buffer = new Byte[];
int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(), FileName);
//必须设定0(系统默认的代码页)的编码方式,否则无法支持中文
string s = Encoding.GetEncoding().GetString(Buffer);
s = s.Substring(, bufLen);
return s.Trim();
} //读整数
public int ReadInteger(string Section, string Ident, int Default)
{
string intStr = ReadString(Section, Ident, Convert.ToString(Default));
try
{
return Convert.ToInt32(intStr);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return Default;
}
} //写整数
public void WriteInteger(string Section, string Ident, int Value)
{
WriteString(Section, Ident, Value.ToString());
} //读布尔
public bool ReadBool(string Section, string Ident, bool Default)
{
try
{
return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return Default;
}
} //写Bool
public void WriteBool(string Section, string Ident, bool Value)
{
WriteString(Section, Ident, Convert.ToString(Value));
} //从Ini文件中,将指定的Section名称中的所有Ident添加到列表中
public void ReadSection(string Section, StringCollection Idents)
{
Byte[] Buffer = new Byte[];
//Idents.Clear(); int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(), FileName);
//对Section进行解析
GetStringsFromBuffer(Buffer, bufLen, Idents);
} private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)
{
Strings.Clear();
if (bufLen != )
{
int start = ;
for (int i = ; i < bufLen; i++)
{
if ((Buffer[i] == ) && ((i - start) > ))
{
String s = Encoding.GetEncoding().GetString(Buffer, start, i - start);
Strings.Add(s);
start = i + ;
}
}
}
} //从Ini文件中,读取所有的Sections的名称
public void ReadSections(StringCollection SectionList)
{
//Note:必须得用Bytes来实现,StringBuilder只能取到第一个Section
byte[] Buffer = new byte[];
int bufLen = ;
bufLen = GetPrivateProfileString(null, null, null, Buffer,
Buffer.GetUpperBound(), FileName);
GetStringsFromBuffer(Buffer, bufLen, SectionList);
} //读取指定的Section的所有Value到列表中
public void ReadSectionValues(string Section, NameValueCollection Values)
{
StringCollection KeyList = new StringCollection();
ReadSection(Section, KeyList);
Values.Clear();
foreach (string key in KeyList)
{
Values.Add(key, ReadString(Section, key, ""));
}
} /**/
////读取指定的Section的所有Value到列表中,
//public void ReadSectionValues(string Section, NameValueCollection Values,char splitString)
//{ string sectionValue;
// string[] sectionValueSplit;
// StringCollection KeyList = new StringCollection();
// ReadSection(Section, KeyList);
// Values.Clear();
// foreach (string key in KeyList)
// {
// sectionValue=ReadString(Section, key, "");
// sectionValueSplit=sectionValue.Split(splitString);
// Values.Add(key, sectionValueSplit[0].ToString(),sectionValueSplit[1].ToString());
// }
//} //清除某个Section
public void EraseSection(string Section)
{
if (!WritePrivateProfileString(Section, null, null, FileName))
{
throw (new ApplicationException("无法清除Ini文件中的Section"));
}
} //删除某个Section下的键
public void DeleteKey(string Section, string Ident)
{
WritePrivateProfileString(Section, Ident, null, FileName);
} //Note:对于Win9X,来说需要实现UpdateFile方法将缓冲中的数据写入文件
//在Win NT, 2000和XP上,都是直接写文件,没有缓冲,所以,无须实现UpdateFile
//执行完对Ini文件的修改之后,应该调用本方法更新缓冲区。
public void UpdateFile()
{
WritePrivateProfileString(null, null, null, FileName);
} //检查某个Section下的某个键值是否存在
public bool ValueExists(string Section, string Ident)
{
StringCollection Idents = new StringCollection();
ReadSection(Section, Idents);
return Idents.IndexOf(Ident) > -;
} //确保资源的释放
~IniFiles()
{
UpdateFile();
}
}
}
ini文件注意点:采用此类读取ini文件的时候首行必须空一行
[Parm]
xxxx =2016-01-08 16:42:04
IsOver =-1
EndTime =2016-01-11 11:30:08
C#读取ini文件的方法的更多相关文章
- C# 读取ini文件,读不出来原因
先赋上相关读取ini文件代码 public class INIHelper { public string inipath; [DllImport("kernel32")] pri ...
- C# 读取ini文件 百度问问学习文档
C# 读取ini文件 10 有多个section,现想读取整个ini文件和指定section下所有内容 补充: 发布答案可以,请对准题目啊,我不要指定节点的内容,我知道!我要的是读取指定区域的内容,假 ...
- delphi读取ini文件
ini文件在系统配置及应用程序参数保存与设置方面,具有很重要的作用,所以可视化的编程一族,如vb.vc.vfp.delphi等都提供了读写ini文件的方法,其中delphi中操作ini文件,最为简洁, ...
- python中configparser模块读取ini文件
python中configparser模块读取ini文件 ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(se ...
- php中读取大文件实现方法详解
php中读取大文件实现方法详解 来源: 时间:2013-09-05 19:27:01 阅读数:6186 分享到:0 [导读] 本文章来给各位同学介绍php中读取大文件实现方法详解吧,有需要了解 ...
- Python基础之读取ini文件
基本使用方法 第一步:准备一份INI文件.如test1.ini [ITEMS] item1=1 item2=2 item3=3 item4=4 [ITEM1] test1=aaa [ITEM2] te ...
- Javascript写入txt和读取txt文件的方法
文章主要介绍了Javascript写入txt和读取txt文件的方法,需要的朋友可以参考下1. 写入 FileSystemObject可以将文件翻译成文件流. 第一步: 例: 复制代码 代码如下: Va ...
- C#中常用的几种读取XML文件的方法
1.C#中常用的几种读取XML文件的方法:http://blog.csdn.net/tiemufeng1122/article/details/6723764/
- Spark Scala 读取GBK文件的方法
1. 在生产环境下,很多文件是GBK编码格式的,而SPARK 常用的textFile方法默认是写死了读UTF-8格式的文件,其他格式文件会显示乱码 用如下代码实现读取GBK文件的方法 import o ...
随机推荐
- 趣味GPS
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 简介 GPS的全称是全球定位系统(the Global Positioning S ...
- 从零开始编写自己的C#框架(10)——项目实施计划与甘特图
不知不觉本系列已经写了一个月,编码前的各项工作到此也终于结束了.回头看看这一个月走过来,白天上班晚上码字查资料,写写改改,挺不容易的.很多时候有些知识会用,知道是怎么回事,但并不等于能写出来.错别字. ...
- IOS开发之微信山寨版
为了犒劳自己的学习内容,就山寨个微信的视图控制吧.拿着微信,仔细的看了一下,主要用到了TabBarController以及配置TabBarItem, NavigationController以及配置N ...
- 教你如何塑造JavaScript牛逼形象
如何写JavaScript才能逼格更高呢?怎样才能组织JavaScript才能让别人一眼看出你不简单呢?是否很期待别人在看完你的代码之后感叹一句“原来还可以这样写”呢?下面列出一些在JavaScrip ...
- 【记录】SqlBulkCopy 跨数据库,表自定义导入
使用场景: 一个数据库中的表数据,导入到另一个数据库中的表中,这两个表的表结构不一样,如果表结构一样的时候,导入非常简单,直接读取导入就行了,表结构不一样,就意味着需要加入一些判断,SqlBulkCo ...
- spring控制并发数的工具类ConcurrencyThrottleSupport和ConcurrencyThrottleInterceptor
官方文档: /** * Support class for throttling concurrent access to a specific resource. * * <p>Desi ...
- Cesium应用篇:3控件(2)BaseLayerPicker
所有范例均在github中搜索:ExamplesforCesium BaseLayerPicker控件非常简单,似乎没什么可说的,确实非常的简单,但作为一个底图选择控件,可以说是最基本的一个控件. C ...
- C#二进制流的序列化和反序列化
public class BinaryHelper { /// <summary> /// 将对象序列化为byte[] /// 使用IFormatter的Serialize序列化 /// ...
- Lucene.net初探
引言 在分析同事开发的客户端搜索项目时注意到,搜索的关键是索引,而提到索引就不得不提Lucene.net,思路就是将需要搜索内容写入索引,客户端自己或局域网其他机器搜索时直接搜索索引,从而查看到你共享 ...
- 用javascript编写的小游戏(getElementById , setInterval , clearInterval , window.onload , innerText 和页面跳转, 标签的使用)
(1)图片轮转 <script type="text/javascript" > ; setInterval(function(){ var dom=document. ...