C# 读写ini文件

由于C#的类库中并不包含读取INI文件的类,用C#读取INI文件必须要用到windows的API函数,所以在声明windows的API函数时必须

  1. using System.Runtime.InteropServices;
  2.     [DllImport("kernel32")]
  3.         private static extern bool WritePrivateProfileString(
  4.             string lpAppName,
  5.             string lpKeyName,
  6.             string lpString,
  7.             string lpFileName
  8.         );
  9.      [DllImport("kernel32")]
            private static extern int GetPrivateProfileString(
                string section,
                string key,
                string def,
                StringBuilder retVal,
                int size,
                string filePath
            );

一.将信息写入.INI文件中.
  1.所用的WINAPI函数原型为:

  1. BOOL WritePrivateProfileString(
  2.      LPCTSTR lpAppName,
  3.      LPCTSTR lpKeyName,
  4.      LPCTSTR lpString,
  5.      LPCTSTR lpFileName
  6. ); 

  其中各参数的意义:
   LPCTSTR lpAppName 是INI文件中的一个字段名.
   LPCTSTR lpKeyName 是lpAppName下的一个键名,通俗讲就是变量名.
   LPCTSTR lpString 是键值,也就是变量的值,不过必须为LPCTSTR型或CString型的.
   LPCTSTR lpFileName 是完整的INI文件名.

 

  2.具体使用方法:设现有一名学生,需把他的姓名和年龄写入 c:/test.ini 文件中.

  1. string strName,;
    • strName = "张三";
    • WritePrivateProfileString("StudentInfo""Name", strName, "C://test.ini");

        此时c:/test.ini 文件中的内容如下:
            [StudentInfo]
   Name=张三

 

二.将信息从INI文件中读入程序中的变量.
  1.所用的WINAPI函数原型为:


  DWORD GetPrivateProfileString(
    LPCTSTR lpAppName,
    LPCTSTR lpKeyName,
    LPCTSTR lpDefault,
    LPTSTR lpReturnedString,
    DWORD nSize,
    LPCTSTR lpFileName
  );


  其中各参数的意义:
   前二个参数与 WritePrivateProfileString中的意义一样.

   lpDefault : 如果INI文件中没有前两个参数指定的字段名或键名,则将此值赋给变量.
   lpReturnedString : 接收INI文件中的值的String对象,即目的缓存器.
   nSize : 目的缓存器的大小.
   lpFileName : 是完整的INI文件名.

 

  2.具体使用方法:现要将上一步中写入的学生的信息读入程序中.

  1. StringBuilder strStudName = new StringBuilder(100);
  2. GetPrivateProfileString("StudentInfo", "Name","默认姓名", strStudName, 100, "c://test.ini"); 

      执行后 strStudName 的值为:"张三",若前两个参数有误,其值为:"默认姓名".


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值