• C#读写INI文件


    最近在编写一些小程序的时候要用到一些配置文件,以前一直用XML或者CONFIG文件,但是发现INI文件特别好用!所以记下来~~~以下内容来自网络整理! 

    由于C#的类库中并不包含读取INI文件的类,用C#读取INI文件必须要用到windowsAPI函数,所以在声明windowsAPI函数时必须这样声明一下。

    [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文件在系统配置及应用程序参数保存与设置方面,具有很重要的作用,所以可视化的编程一族,如VBVCVFPDelphi等都提供了读写INI文件的方法,其中Delphi中操作INI文件,最为简洁,这是因为Delphi3提供了一个TInifile类,使我们可以非常灵活的处理INI文件。 

    一、有必要了解INI文件的结构:
    ;注释
    [小节名]
    关键字=
    ...
      INI文件允许有多个小节,每个小节又允许有多个关键字, "="后面是该关键字的值。 
      值的类型有三种:字符串、整型数值和布尔值。其中字符串存贮在INI文件中时没有引号,
    布尔真值用1表示,布尔假值用0表示。 
      注释以分号";"开头。 
    二、定义
      1、在InterfaceUses节增加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文件中关键字的值。 
      假设已定义变量vsvivb分别为string、 integerboolean类型。  

    vs:=myinifile.Readstring('小节名','关键字',缺省值);
    vi:=myinifile.Readinteger('小节名','关键字',缺省值);
    vb:=myinifile.Readbool('小节名','关键字',缺省值);

      其中缺省值为该INI文件不存在该关键字时返回的缺省值。 

    五、写入INI文件
      同样的,TInifile类也提供了三种不同的对象方法,向INI文件写入字符串、整型数及布尔类型的关键字。  

    myinifile.writestring('小节名','关键字',变量或字符串值);
    myinifile.writeinteger('小节名','关键字',变量或整型数值);
    myinifile.writebool('小节名','关键字',变量或TrueFalse);
      当这个INI文件不存在时,上面的语句还会自动创建该INI文件。 
    六、删除关键字
      除了可用写入方法增加一个关键字,Tinifile类还提供了一个删除关键字的对象方法: 
    myinifile.DeleteKey('小节名','关键字');

    七、小节操作
      增加一个小节可用写入的方法来完成,删除一个小节可用下面的对象方法: 
          myinifile.EraseSection('小节名');
      另外Tinifile类还提供了三种对象方法来对小节进行操作: 
      myinifile.readsection('小节名',TStrings变量);可将指定小节中的所有关键字名读取至一个字符串列表变量中; 
      myinifile.readsections(TStrings变量);可将INI文件中所有小节名读取至一个字符串列表变量中去。 
      myinifile.readsectionvalues('小节名',TStrings变量);可将INI文件中指定小节的所有行(包括关键字、=、值)读取至一个字符串列表变量中去。

    八、释放
    在适当的位置用下面的语句释放myinifile:
    myinifile.distory;
    九、一个实例
      下面用一个简单的例子(如图),演示了建立、读取、存贮INI文件的方法。myini.ini文件中包含有"程序参数"小节,和用户名称(字符串)、是否正式用户(布尔值)和已运行时间(整型值)三个关键字。程序在窗体建立读取这些数据,并在窗体释放时写myini.ini文件。 
      附源程序清单 
    unit Unit1;
    interface
    uses
         Windows,Messages,SysUtils,Classes,Graphics,Controls,Forms,Dialogs,inifiles,StdCtrls,ExtCtrls;

    type
         TForm1 = class(TForm)
           Edit1: TEdit;
           CheckBox1: TCheckBox;
           Edit2: TEdit;
           Label1: TLabel;
           Label2: TLabel;
           Timer1: TTimer;
           Label3: TLabel;
           procedure FormCreate(Sender: TObject);
           procedure FormDestroy(Sender: TObject);
           procedure Timer1Timer(Sender: TObject);
         private
           { Private declarations }
         public
           { Public declarations }
         end;
    var
         Form1: TForm1;

    implementation
    var
         myinifile:TInifile;
    {$R *.DFM}

    procedure TForm1.FormCreate(Sender: TObject);
    var filename:string;
    begin
         filename:=ExtractFilePath(paramstr(0))+'myini.ini';
         myinifile:=TInifile.Create(filename);
         edit1.Text:= myinifile.readstring('程序参数','用户名称','缺省的用户名称');
         edit2.text:= inttostr(myinifile.readinteger('程序参数','已运行时间',0));
         checkbox1.Checked:= myinifile.readbool('程序参数','是否正式用户',False);
    end;

    procedure TForm1.FormDestroy(Sender: TObject);
    begin
         myinifile.writestring('程序参数','用户名称',edit1.Text);

         myinifile.writeinteger('程序参数','已运行时间',strtoint(edit2.text));
         myinifile.writebool('程序参数','是否正式用户',checkbox1.Checked);
         myinifile.Destroy;
    end;

    procedure TForm1.Timer1Timer(Sender: TObject);
    begin
         edit2.Text:=inttostr(strtoint(edit2.text)+1);
    end;

    end.

    当用C#读入是只要[DllImport("kernel32")]声明,用法差不多

    using System;

    using System.IO;

    using System.Runtime.InteropServices;

    using System.Text;

    namespace EchonComponentLibrary

    {

        /// 

        /// IniFile 的摘要说明。

        /// 

        public class IniFile

        {

            private string FFileName;

            [DllImport("kernel32")]

            private static extern int GetPrivateProfileInt(

            string lpAppName,

            string lpKeyName,

            int nDefault,

            string lpFileName

            );

            [DllImport("kernel32")]

            private static extern int GetPrivateProfileString(

            string lpAppName,

            string lpKeyName,

            string lpDefault,

            StringBuilder lpReturnedString,

            int nSize,

            string lpFileName

            );

            [DllImport("kernel32")]

            private static extern bool WritePrivateProfileString(

            string lpAppName,

            string lpKeyName,

            string lpString,

            string lpFileName

            );

            public IniFile(string filename)

            {

                FFileName = filename;

            }

            public int ReadInt(string section, string key, int def)

            {

                return GetPrivateProfileInt(section, key, def, FFileName);

            }

            public string ReadString(string section, string key, string def)

            {

                StringBuilder temp = new StringBuilder(1024);

                GetPrivateProfileString(section, key, def, temp, 1024, FFileName);

                return temp.ToString();

            }

            public void WriteInt(string section, string key, int iVal)

            {

                WritePrivateProfileString(section, key, iVal.ToString(), FFileName);

            }

            public void WriteString(string section, string key, string strVal)

            {

                WritePrivateProfileString(section, key, strVal, FFileName);

            }

            public void DelKey(string section, string key)

            {

                WritePrivateProfileString(section, key, null, FFileName);

            }

            public void DelSection(string section)

            {

                WritePrivateProfileString(section, null, null, FFileName);

            }

        }

        class Program

        {

            static void Main(string[] args)

            {

                IniFile g = new IniFile("D:\\newton毕设\\testpro\\c#\\ConsoleApplication6\\ConsoleApplication6\\bin\\Debug\\test.ini");

     

                g.WriteInt("kkkk", "age", 12);

                g.WriteInt("kkkk", "page", 37);

                g.WriteString("ffff", "mayname", "newton");

                int b = g.ReadInt("kkkk", "page", 50);

                string s = g.ReadString("fffffd", "mayname", "11");

                Console.WriteLine(b.ToString());

                Console.WriteLine(s.ToString());

            }

        }

    }

    参考资料:

    -------------------------------------------------------------------------------------------------------------------------------------------------
    数据库优化
    数据库教程
    数据库实战经验分享博客

    百度云下载

    评测


  • 相关阅读:
    Codeforces Round #502 (in memory of Leopoldo Taravilse, Div. 1 + Div. 2) E. The Supersonic Rocket
    Codeforces Round #500 (Div. 2) D
    AtCoder Grand Contest 026 D
    Codeforces Round #495 (Div. 2) Sonya and Matrix
    AtCoder Regular Contest 100 E
    1013 数素数
    1010 一元多项式求导(用while接收输入)
    1009 说反话(字符串、栈)
    L2-006 树的遍历 (后序中序求层序)
    L2-004 这是二叉搜索树吗?
  • 原文地址:https://www.cnblogs.com/longle/p/ini.html
Copyright © 2020-2023  润新知