由于C#的类库中并不包含读取INI文件的类,用C#读取INI文件必须要用到windows的API函数,所以在声明windows的API函数时必须
[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(
string lpAppName,
string lpKeyName,
string lpString,
string lpFileName
);
这样声明一下。
下面分别介绍一下读取INI文件的windows API函数(“ ”中为我在网上找到的信息)
“ 一.将信息写入.INI文件中.
1.所用的WINAPI函数原型为:
BOOL WritePrivateProfileString(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
LPCTSTR lpString,
LPCTSTR lpFileName
);
其中各参数的意义:
LPCTSTR lpAppName 是INI文件中的一个字段名.
LPCTSTR lpKeyName 是lpAppName下的一个键名,通俗讲就是变量名.
LPCTSTR lpString 是键值,也就是变量的值,不过必须为LPCTSTR型或CString型的.
LPCTSTR lpFileName 是完整的INI文件名.
2.具体使用方法:设现有一名学生,需把他的姓名和年龄写入 c:\stud\student.ini 文件中.
CString strName,strTemp;
int nAge;
strName="张三";
nAge=12;
::WritePrivateProfileString("StudentInfo","Name",strName,"c:\\stud\\student.ini");
此时c:\stud\student.ini文件中的内容如下:
[StudentInfo]
Name=张三
3.要将学生的年龄保存下来,只需将整型的值变为字符型即可:
strTemp.Format("%d",nAge);
::WritePrivateProfileString("StudentInfo","Age",strTemp,"c:\\stud\\student.ini");
二.将信息从INI文件中读入程序中的变量.
1.所用的WINAPI函数原型为:
DWORD GetPrivateProfileString(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
LPCTSTR lpDefault,
LPTSTR lpReturnedString,
DWORD nSize,
LPCTSTR lpFileName
);
其中各参数的意义:
前二个参数与 WritePrivateProfileString中的意义一样.
lpDefault : 如果INI文件中没有前两个参数指定的字段名或键名,则将此值赋给变量.
lpReturnedString : 接收INI文件中的值的CString对象,即目的缓存器.
nSize : 目的缓存器的大小.
lpFileName : 是完整的INI文件名.
2.具体使用方法:现要将上一步中写入的学生的信息读入程序中.
CString strStudName;
int nStudAge;
GetPrivateProfileString("StudentInfo","Name","默认姓名",strStudName.GetBuffer(MAX_PATH),MAX_PATH,"c:\\stud\\student.ini");
执行后 strStudName 的值为:"张三",若前两个参数有误,其值为:"默认姓名".
3.读入整型值要用另一个WINAPI函数:
UINT GetPrivateProfileInt(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
INT nDefault,
LPCTSTR lpFileName
);
这里的参数意义与上相同.使用方法如下:
nStudAge=GetPrivateProfileInt("StudentInfo","Age",10,"c:\\stud\\student.ini");
三.循环写入多个值,设现有一程序,要将最近使用的几个文件名保存下来,具体程序如下:
1.写入:
CString strTemp,strTempA;
int i;
int nCount=6;
file://共有6个文件名需要保存
for(i=0;i {strTemp.Format("%d",i);
strTempA=文件名;
file://文件名可以从数组,列表框等处取得.
::WritePrivateProfileString("UseFileName","FileName"+strTemp,strTempA,"c:\\usefile\\usefile.ini");
}
strTemp.Format("%d",nCount);
::WritePrivateProfileString("FileCount","Count",strTemp,"c:\\usefile\\usefile.ini");
file://将文件总数写入,以便读出.
2.读出:
nCount=::GetPrivateProfileInt("FileCount","Count",0,"c:\\usefile\\usefile.ini");
for(i=0;i {strTemp.Format("%d",i);
strTemp="FileName"+strTemp;
::GetPrivateProfileString("CurrentIni",strTemp,"default.fil", strTempA.GetBuffer(MAX_PATH),MAX_PATH,"c:\\usefile\\usefile.ini");
file://使用strTempA中的内容.
}
补充四点:
1.INI文件的路径必须完整,文件名前面的各级目录必须存在,否则写入不成功,该函数返回 FALSE 值.
2.文件名的路径中必须为 \\ ,因为在VC++中, \\ 才表示一个 \ .
3.也可将INI文件放在程序所在目录,此时 lpFileName 参数为: ".\\student.ini".
4.从网页中粘贴源代码时,最好先粘贴至记事本中,再往VC中粘贴,否则易造成编译错误,开始时我也十分不解,好好的代码怎么就不对呢?后来才找到这个方法.还有一些代码中使用了全角字符如:<,\等,也会
造成编译错误.
INI文件编程
INI文件在系统配置及应用程序参数保存与设置方面,具有很重要的作用,所以可视化的编程一族,如VB、VC、VFP、Delphi等都提供了读写INI文件的方法,其中Delphi中操作INI文件,最为简洁,这是因为Delphi3提供了一个TInifile类,使我们可以非常灵活的处理INI文件。
一、有必要了解INI文件的结构:
;注释
[小节名]
关键字=值
...
INI文件允许有多个小节,每个小节又允许有多个关键字, "="后面是该关键字的值。
值的类型有三种:字符串、整型数值和布尔值。其中字符串存贮在INI文件中时没有引号,
布尔真值用1表示,布尔假值用0表示。
注释以分号";"开头。
二、定义
1、在Interface的Uses节增加IniFiles;
2、在Var变量定义部分增加一行:
myinifile:Tinifile;
然后,就可以对变量myinifile进行创建、打开、读取、写入等操作了。
三、打开INI文件
myinifile:=Tinifile.create('program.ini');
上面这一行语句将会为变量myinifile与具体的文件 program.ini建立联系,然后,就可以通过变量myinifile,来读写program.ini文件中的关键字的值了。值得注意的是,如果括号中的文件名没有指明路径的话,那么这个Program.ini文件会存储在Windows目录中,把Program.ini文件存储在应用程序当前目录中的方法是:为其指定完整的路径及文件名。下面的两条语句可以完成这个功能:
Filename:=ExtractFilePath(Paramstr(0))+'program.ini';
myinifile:=Tinifile.Create(filename);
四、读取关键字的值
针对INI文件支持的字符串、整型数值、布尔值三种数据类型,TINIfiles类提供了三种不同的对象方法来读取INI文件中关键字的值。
假设已定义变量vs、vi、vb分别为string、 integer、boolean类型。
vs:=myinifile.Readstring('小节名','关键字',缺省值);
vi:=myinifile.Readinteger('小节名','关键字',缺省值);
vb:=myinifile.Readbool('小节名','关键字',缺省值);
其中缺省值为该INI文件不存在该关键字时返回的缺省值。
五、写入INI文件
同样的,TInifile类也提供了三种不同的对象方法,向INI文件写入字符串、整型数及布尔类型的关键字。
myinifile.writestring('小节名','关键字',变量或字符串值);
myinifile.writeinteger('小节名','关键字',变量或整型数值);
myinifile.writebool('小节名','关键字',变量或True或False);
当这个INI文件不存在时,上面的语句还会自动创建该INI文件。
六、删除关键字
除了可用写入方法增加一个关键字,Tinifile类还提供了一个删除关键字的对象方法:
myinifile.DeleteKey('小节名','关键字');
七、小节操作
增加一个小节可用写入的方法来完成,删除一个小节可用下面的对象方法:
myinifile.EraseSection('小节名');
另外Tinifile类还提供了三种对象方法来对小节进行操作:
myinifile.readsection('小节名',TStrings变量);可将指定小节中的所有关键字名读取至一个字符串列表变量中;
myinifile.readsections(TStrings变量);可将INI文件中所有小节名读取至一个字符串列表变量中去。
myinifile.readsectionvalues('小节名',TStrings变量);可将INI文件中指定小节的所有行(包括关键字、=、值)读取至一个字符串列表变量中去。
八、释放
在适当的位置用下面的语句释放myinifile:
myinifile.distory;
C# 读写InI的类2007年05月21日 星期一 16:54using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace IniFiles
{
public abstract class CustomIniFile
{
public CustomIniFile(string AFileName)
{
FFileName = AFileName;
}
private string FFileName;
public string FileName
{
get { return FFileName; }
}
public virtual bool SectionExists(string Section)
{
List vStrings = new List();
ReadSections(vStrings);
return vStrings.Contains(Section);
}
public virtual bool ValueExists(string Section, string Ident)
{
List vStrings = new List();
ReadSection(Section, vStrings);
return vStrings.Contains(Ident);
}
public abstract string ReadString(string Section, string Ident, string Default);
public abstract bool WriteString(string Section, string Ident, string Value);
public abstract bool ReadSectionValues(string Section, List Strings);
public abstract bool ReadSection(string Section, List Strings);
public abstract bool ReadSections(List Strings);
public abstract bool EraseSection(string Section);
public abstract bool DeleteKey(string Section, string Ident);
public abstract bool UpdateFile();
}
///
/// 存储本地INI文件的类。
///
public class IniFile : CustomIniFile
{
[DllImport("kernel32")]
private static extern uint GetPrivateProfileString(
string lpAppName,// points to section name
string lpKeyName,// points to key name
string lpDefault,// points to default string
byte[] lpReturnedString,// points to destination buffer
uint nSize,// size of destination buffer
string lpFileName // points to initialization filename
);
[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(
string lpAppName,// pointer to section name
string lpKeyName,// pointer to key name
string lpString,// pointer to string to add
string lpFileName // pointer to initialization filename
);
///
/// 构造IniFile实例。
/// 指定文件名
/// public IniFile(string AFileName)
: base(AFileName)
{
}
///
/// 析够IniFile实例。
///
~IniFile()
{
UpdateFile();
}
///
/// 读取字符串值。
/// 指定变量标识。
/// 指定所在区域。
/// 指定默认值。
/// 返回读取的字符串。如果读取失败则返回该值。
/// public override string ReadString(string Section, string Ident, string Default)
{
byte[] vBuffer = new byte[2048];
uint vCount = GetPrivateProfileString(Section,
Ident, Default, vBuffer, (uint)vBuffer.Length, FileName);
return Encoding.Default.GetString(vBuffer, 0, (int)vCount);
}
///
/// 写入字符串值。
/// ///
指定所在区域。
///
指定变量标识。
///
所要写入的变量值。
///
返回写入是否成功。 public override bool WriteString(string Section, string Ident, string Value)
{
return WritePrivateProfileString(Section, Ident, Value, FileName);
}
///
/// 获得区域的完整文本。(变量名=值格式)。
/// ///
指定区域标识。
///
输出处理结果。
///
返回读取是否成功。 public override bool ReadSectionValues(string Section, List
Strings)
{
List vIdentList = new List();
if (!ReadSection(Section, vIdentList)) return false;
foreach (string vIdent in vIdentList)
Strings.Add(string.Format("{0}={1}", vIdent, ReadString(Section, vIdent, "")));
return true;
}
///
/// 读取区域变量名列表。
/// ///
指定区域名。
///
指定输出列表。
///
返回获取是否成功。 public override bool ReadSection(string Section, List
Strings)
{
byte[] vBuffer = new byte[16384];
uint vLength = GetPrivateProfileString(Section, null, null, vBuffer,
(uint)vBuffer.Length, FileName);
int j = 0;
for (int i = 0; i < vLength; i++)
if (vBuffer[i] == 0)
{
Strings.Add(Encoding.Default.GetString(vBuffer, j, i - j));
j = i + 1;
}
return true;
}
///
/// 读取区域名列表。
/// ///
指定输出列表。
///
public override bool ReadSections(List
Strings)
{
byte[] vBuffer = new byte[16384];
uint vLength = GetPrivateProfileString(null, null, null, vBuffer,
(uint)vBuffer.Length, FileName);
int j = 0;
for (int i = 0; i < vLength; i++)
if (vBuffer[i] == 0)
{
Strings.Add(Encoding.Default.GetString(vBuffer, j, i - j));
j = i + 1;
}
return true;
}
///
/// 删除指定区域。
/// ///
指定区域名。
///
返回删除是否成功。 public override bool EraseSection(string Section)
{
return WritePrivateProfileString(Section, null, null, FileName);
}
///
/// 删除指定变量。
/// ///
变量所在区域。
///
变量标识。
///
返回删除是否成功。 public override bool DeleteKey(string Section, string Ident)
{
return WritePrivateProfileString(Section, Ident, null, FileName);
}
///
/// 更新文件。
///
/// 返回更新是否成功。
public override bool UpdateFile()
{
return WritePrivateProfileString(null, null, null, FileName);
}
}
}
//通过SectionExists()可以知道