c#读写Ini文件

来源:互联网 发布:java二级考试内容 编辑:程序博客网 时间:2024/05/17 07:04

 

INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value)

  [Section]

  Key=Value

 

VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法。因为我们需要调用API函数,所以必须创建System.Runtime.InteropServices 命名空间以提供可用于访问 .NET 中的 COM 对象和本机 API 的类的集合。

 

客户端调用:

API说明:

BOOL WritePrivateProfileString(

    LPCTSTR lpAppName, // 节名

    LPCTSTR lpKeyName, // 键名

    LPCTSTR lpString, // 添加的字符串

    LPCTSTR lpFileName  // Ini文件名

   );

BOOL WritePrivateProfileStruct(

    LPCTSTR lpszSection, // pointer to section name

    LPCTSTR lpszKey, // pointer to key name

    LPVOID lpStruct, // 要写入的数据缓冲区

    UINT uSizeStruct, // 缓冲区的大小

    LPCTSTR szFile // pointer to initialization filename

   );

BOOL WritePrivateProfileSection(

    LPCTSTR lpAppName, // pointer to string with section name

    LPCTSTR lpString, // 写入的字符串

    LPCTSTR lpFileName  // pointer to string with filename

   );

用API读INI文件的函数有

DWORD GetPrivateProfileString(

    LPCTSTR lpAppName, // points to section name

    LPCTSTR lpKeyName, // points to key name

    LPCTSTR lpDefault, // 默认字符串 ,如果没有则返回该值

    LPTSTR lpReturnedString, // 返回的字符串

    DWORD nSize, // 返回字符串的大小

    LPCTSTR lpFileName  // points to initialization filename

   );

DWORD GetPrivateProfileSection(

    LPCTSTR lpAppName, // address of section name

    LPTSTR lpReturnedString, // address of return buffer

    DWORD nSize, // size of return buffer

    LPCTSTR lpFileName  // address of initialization filename  

   );

UINT GetPrivateProfileInt(

    LPCTSTR lpAppName, // address of section name

    LPCTSTR lpKeyName, // address of key name

    INT nDefault, // return value if key name is not found

    LPCTSTR lpFileName  // address of initialization filename

   ); 

BOOL GetPrivateProfileStruct(

    LPCTSTR lpszSection, // address of section name

    LPCTSTR lpszKey, // address of key name

    LPVOID lpStruct, // address of return buffer

    UINT uSizeStruct, // size of return buffer

    LPCTSTR szFile // address of initialization filename

   );

DWORD GetPrivateProfileSectionNames(

    LPTSTR lpszReturnBuffer, // address of return buffer

    DWORD nSize, // size of return buffer

    LPCTSTR lpFileName // address of initialization filename

   );

当然还有如WriteProfileString,WriteProfileSection,WriteProfileSturct, GetProfileString,GetProfileStruct,GetProfileSectionNames,GetProfileInt,GetProfileSection但这些只对Win.ini有效

下面我们来学习它们的用法

WritePrivateProfileString函数是向ini文件中写入字符串,如

WritePrivateProfileString(Pchar('类型'),Pchar('API'),Pchar('API 真好!'),Pchar('c:/example.ini'));

如果第二个参数是nil,那么该操作将删除该节

如果第三个参数为nil,那么该操作将删除该节中的所有键

如果在指定的文件中没有路径,那么它将在系统的目录寻找文件,如果不存在则建立

原创粉丝点击