最近项目用到ini文件,读取ini文件,方法如下:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Collections.Specialized;usingSystem.IO;usingSystem.Runtime.InteropServices;usingSystem.Windows.Forms;namespacetest{///<summary>///IniFiles的类///</summary>publicclassIniFiles
{publicstringFileName;//INI文件名//string path = System.IO.Path.Combine(application.StartupPath,"pos.ini");//声明读写INI文件的API函数[DllImport("kernel32")]PRivatestaticexternboolWritePrivateProfileString(stringsection,stringkey,stringval,stringfilePath);
[DllImport("kernel32")]privatestaticexternintGetPrivateProfileString(stringsection,stringkey,stringdef,byte[] retVal,intsize,stringfilePath);//类的构造函数,传递INI文件名publicIniFiles(stringAFileName)
{//判断文件是否存在FileInfo fileInfo =newFileInfo(AFileName);//Todo:搞清枚举的用法if((!fileInfo.Exists))
{//|| (FileAttributes.Directory in fileInfo.Attributes))//文件不存在,建立文件System.IO.StreamWriter sw =newSystem.IO.StreamWriter(AFileName,false, System.Text.Encoding.Default);try{
sw.Write("#表格配置档案");
sw.Close();
}catch{throw(newApplicationException("Ini文件不存在"));
}
}//必须是完全路径,不能是相对路径FileName =fileInfo.FullName;
}//写INI文件publicvoidWriteString(stringSection,stringIdent,stringValue)
{if(!WritePrivateProfileString(Section, Ident, Value, FileName))
{throw(newApplicationException("写Ini文件出错"));
}
}//读取INI文件指定publicstringReadString(stringSection,stringIdent,stringDefault)
{
Byte[] Buffer=newByte[65535];intbufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName);//必须设定0(系统默认的代码页)的编码方式,否则无法支持中文strings = Encoding.GetEncoding(0).GetString(Buffer);
s= s.Substring(0, bufLen);returns.Trim();
}//读整数publicintReadInteger(stringSection,stringIdent,intDefault)
{stringintStr =ReadString(Section, Ident, Convert.ToString(Default));try{returnConvert.ToInt32(intStr);
}catch(Exception ex)
{
Console.WriteLine(ex.Message);returnDefault;
}
}//写整数publicvoidWriteInteger(stringSection,stringIdent,intValue)
{
WriteString(Section, Ident, Value.ToString());
}//读布尔publicboolReadBool(stringSection,stringIdent,boolDefault)
{try{returnConvert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));
}catch(Exception ex)
{
Console.WriteLine(ex.Message);returnDefault;
}
}//写BoolpublicvoidWriteBool(stringSection,stringIdent,boolValue)
{
WriteString(Section, Ident, Convert.ToString(Value));
}//从Ini文件中,将指定的Section名称中的所有Ident添加到列表中publicvoidReadSection(stringSection, StringCollection Idents)
{
Byte[] Buffer=newByte[16384];//Idents.Clear();intbufLen = GetPrivateProfileString(Section,null,null, Buffer, Buffer.GetUpperBound(0), FileName);//对Section进行解析GetStringsFromBuffer(Buffer, bufLen, Idents);
}privatevoidGetStringsFromBuffer(Byte[] Buffer,intbufLen, StringCollection Strings)
{
Strings.Clear();if(bufLen !=0)
{intstart =0;for(inti =0; i < bufLen; i++)
{if((Buffer[i] ==0) && ((i - start) >0))
{
String s= Encoding.GetEncoding(0).GetString(Buffer, start, i -start);
Strings.Add(s);
start= i +1;
}
}
}
}//从Ini文件中,读取所有的Sections的名称publicvoidReadSections(StringCollection SectionList)
{//Note:必须得用Bytes来实现,StringBuilder只能取到第一个Sectionbyte[] Buffer =newbyte[65535];intbufLen =0;
bufLen= GetPrivateProfileString(null,null,null, Buffer,
Buffer.GetUpperBound(0), FileName);
GetStringsFromBuffer(Buffer, bufLen, SectionList);
}//读取指定的Section的所有Value到列表中publicvoidReadSectionValues(stringSection, NameValueCollection Values)
{
StringCollection KeyList=newStringCollection();
ReadSection(Section, KeyList);
Values.Clear();foreach(stringkeyinKeyList)
{
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());//}//}//清除某个SectionpublicvoidEraseSection(stringSection)
{if(!WritePrivateProfileString(Section,null,null, FileName))
{throw(newApplicationException("无法清除Ini文件中的Section"));
}
}//删除某个Section下的键publicvoidDeleteKey(stringSection,stringIdent)
{
WritePrivateProfileString(Section, Ident,null, FileName);
}//Note:对于Win9X,来说需要实现UpdateFile方法将缓冲中的数据写入文件//在Win NT, 2000和XP上,都是直接写文件,没有缓冲,所以,无须实现UpdateFile//执行完对Ini文件的修改之后,应该调用本方法更新缓冲区。publicvoidUpdateFile()
{
WritePrivateProfileString(null,null,null, FileName);
}//检查某个Section下的某个键值是否存在publicboolValueExists(stringSection,stringIdent)
{
StringCollection Idents=newStringCollection();
ReadSection(Section, Idents);returnIdents.IndexOf(Ident) > -1;
}//确保资源的释放~IniFiles()
{
UpdateFile();
}
}
}
ini文件注意点:采用此类读取ini文件的时候首行必须空一行
[Parm]
xxxx =2016-01-08 16:42:04
IsOver =-1
EndTime =2016-01-11 11:30:08