最近项目用到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文件的方法的更多相关文章

  1. C# 读取ini文件,读不出来原因

    先赋上相关读取ini文件代码 public class INIHelper { public string inipath; [DllImport("kernel32")] pri ...

  2. C# 读取ini文件 百度问问学习文档

    C# 读取ini文件 10 有多个section,现想读取整个ini文件和指定section下所有内容 补充: 发布答案可以,请对准题目啊,我不要指定节点的内容,我知道!我要的是读取指定区域的内容,假 ...

  3. delphi读取ini文件

    ini文件在系统配置及应用程序参数保存与设置方面,具有很重要的作用,所以可视化的编程一族,如vb.vc.vfp.delphi等都提供了读写ini文件的方法,其中delphi中操作ini文件,最为简洁, ...

  4. python中configparser模块读取ini文件

    python中configparser模块读取ini文件 ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(se ...

  5. php中读取大文件实现方法详解

    php中读取大文件实现方法详解 来源:   时间:2013-09-05 19:27:01   阅读数:6186 分享到:0 [导读] 本文章来给各位同学介绍php中读取大文件实现方法详解吧,有需要了解 ...

  6. Python基础之读取ini文件

    基本使用方法 第一步:准备一份INI文件.如test1.ini [ITEMS] item1=1 item2=2 item3=3 item4=4 [ITEM1] test1=aaa [ITEM2] te ...

  7. Javascript写入txt和读取txt文件的方法

    文章主要介绍了Javascript写入txt和读取txt文件的方法,需要的朋友可以参考下1. 写入 FileSystemObject可以将文件翻译成文件流. 第一步: 例: 复制代码 代码如下: Va ...

  8. C#中常用的几种读取XML文件的方法

    1.C#中常用的几种读取XML文件的方法:http://blog.csdn.net/tiemufeng1122/article/details/6723764/

  9. Spark Scala 读取GBK文件的方法

    1. 在生产环境下,很多文件是GBK编码格式的,而SPARK 常用的textFile方法默认是写死了读UTF-8格式的文件,其他格式文件会显示乱码 用如下代码实现读取GBK文件的方法 import o ...

随机推荐

  1. 【Win 10应用开发】实现全屏播放的方法

    有人会问,以前的MediaElement控件不是有现成的一排操作按钮吗?而且可以直接进入全屏播放.是的,我们知道,以往的Store App都是在全屏模式下运行的,只要MediaElement控件填满整 ...

  2. 应用程序框架实战三十七:Util最新代码更新说明

    离上一篇又过去了一个月,时间比较紧,后续估计会更紧,所以这次将放出更多公共操作类及配套的CodeSmith模板,本篇将简要介绍新放出的重要功能,供有兴趣的同学参考. 重要更新 这一次对两个VS解决方案 ...

  3. T-SQL:毕业生出门需知系列(六)

    第6课 用通配符进行过滤 6.1 LIKE 操作符 前面介绍的所有操作符都是针对已知值进行过滤.但是,这种过滤方法并不是任何时候都好用. 例如:怎样搜索产品名中包含文本 bean bag 的所有产品? ...

  4. geotrellis使用(三)geotrellis数据处理过程分析

    之前简单介绍了geotrellis的工作过程以及一个简单的demo,最近在此demo的基础上实现了SRTM DEM数据的实时分析以及高程实时处理,下面我就以我实现的上述功能为例,简单介绍一下geotr ...

  5. 介绍一个很爽的 php 字符串特定检索函数---strpos()

    大家在用 php 开发的时候 是否 有遇到过,对于一个获取的字符串,如果想要特定检测它是否 含有某个特定的字符或者子字符串,总是找不到好方法,或者根本做不到,迫于无奈而使用foreach. 函数: s ...

  6. 【url重写】

    一.原理void Application_BeginRequest(object sender, EventArgs e)    {  //url重写        HttpApplication a ...

  7. 浅谈C#中一种类插件系统编写的简单方法(插件间、插件宿主间本身不需要通信)

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/. 1.背景 三年多前还在上研时,用C#+反射机制写过插件系统,后来又用M ...

  8. 理解领域模型Domain Model

    定义 业务对象模型(也叫领域模型 domain model)是描述业务用例实现的对象模型.它是对业务角色和业务实体之间应该如何联系和协作以执行业务的一种抽象.业务对象模型从业务角色内部的观点定义了业务 ...

  9. 如何设置 Panorama 控件的只读 SelectedIndex 属性?

    在 OnNavigatedTo() 方法中设置: panoramaControl.DefaultItem = panoramaControl.Items[indexToSet];

  10. React Native Changed the World? or Nothing.

    RN是一个awesome的技术, facebook很有想法的团队创造出一项新的技术改变了native开发界. 但是RN本身又疑点重重, RN是为了解决什么问题而存在的? 在诞生了一年后, RN又解决了 ...