最近项目用到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. Sql Server系列:Update语句

    1 UPDATE语法结构 [ WITH <common_table_expression> [...n] ] UPDATE [ TOP ( expression ) [ PERCENT ] ...

  2. java基础--java.util.Date类型小结

    首先先来了解一下Date数据类型: . Date类型通常要和另一个 java.text.SimpleDateFormat类联合使用. 把long-->Date: public Date(long ...

  3. C# 将内容写入txt文档

    <1>  FileStream fs = new FileStream(@"D:\text.txt", FileMode.Append); StreamWriter s ...

  4. CSS实现单行与多行文字省略(truncation)

    在上一篇文章小div布局之卡片堆叠(card-stacking)中有多行文字溢出省略的效果,这篇文章就对这种效果(包括单行文字溢出省略)的实现做个简单的记录,以防自己忘记.具体来说,就是要实现这种文字 ...

  5. 【JUC】JUC线程池框架综述

    一.前言 在分析完了JUC的锁和集合框架后,下面进入JUC线程池框架的分析,下面给出JUC线程池的总体框架,之后再逐一进行分析. 二.JUC线程池框架图 说明:从上图可知,JUC线程池框架中的其他接口 ...

  6. mybatis入门基础(八)-----查询缓存

    一.什么是查询缓存 mybatis提供查询缓存,用于减轻数据压力,提高数据库性能. mybaits提供一级缓存,和二级缓存. 1.1. 一级缓存是sqlSession级别的缓存.在操作数据库时需要构造 ...

  7. GitHub托管BootStrap资源汇总(持续更新中…)

    Twitter BootStrap已经火过大江南北,对于无法依赖美工的程序员来说,这一成熟前卫的前端框架简直就一神器,轻轻松松地实现出专业的UI效果.GitHub上相关的的开源项目更是层出不穷,在此整 ...

  8. 【翻译】设计模式学习系列1---【Design Patterns Simplified: Part 1【设计模式简述:第一部分】】

    原文链接:http://www.c-sharpcorner.com/UploadFile/19b1bd/design-patterns-simplified-part1/ Design Pattern ...

  9. C#学习笔记-封装

    前言 说起来惭愧,学了大半年的C#,其实最开始就接触到了封装的部分,但是一直模模糊糊的弄不清楚,也觉得没什么影响就没怎么在意,现在才开始认真的看这部分内容,看懂了过后好多东西清晰了不少,才发现封装这个 ...

  10. php实现hack中的Shape特性

    用php进行静态类型编程,估计是我的一个心结. 依次有几篇文章都记录了我的一些探索: 通过指定函数/方法形参类型提高PHP代码可靠性 http://www.cnblogs.com/x3d/p/4285 ...