C Delphi讀寫INI檔案

2021-05-18 15:32:44 字數 2904 閱讀 7581

(第一次用這種東西)

2007-04-17 09:32

以前無知不知道ini檔案是什麼,畢設需要用到。不得不學著用(據說這種東西是最簡單的初始化函式方法)。

由於c#的類庫中並不包含讀取ini檔案的類,用c#讀取ini檔案必須要用到windows的api函式,所以在宣告windows的api函式時必須

這樣宣告一下。

下面分別介紹一下讀取ini檔案的windows api函式(「 」中為我在網上找到的資訊)

八、釋放

在適當的位置用下面的語句釋放myinifile:

myinifile.distory;

九、乙個例項

下面用乙個簡單的例子(如圖),演示了建立、讀取、存貯ini檔案的方法。myini.ini檔案中包含有"程式引數"小節,和使用者名稱(字串)、是否正式使用者(布林值)和已執行時間(整型值)三個關鍵字。程式在窗體建立讀取這些資料,並在窗體釋放時寫myini.ini檔案。

附源程式清單

unit unit1;

inte***ce

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

public

end;

varform1: tform1;

implementation

varmyinifile:tinifile;

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

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

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

public void writeint(string section, string key, int ival)

public void writestring(string section, string key, string strval)

public void delkey(string section, string key)

public void delsection(string section)

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());}}

}

INI檔案讀寫

一 有必要了解ini檔案的結構 注釋 小節名 關鍵字 值 ini檔案允許有多個小節,每個小節又允許有多個關鍵字,後面是該關鍵字的值。值的型別有三種 字串 整型數值和布林值。其中字串存貯在ini檔案中時沒有引號,布林真值用1表示,布林假值用0表示。注釋以分號 開頭。二 定義 1 在inte ce的us...

讀寫ini檔案

using system using system.io using system.text using system.configuration using system.runtime.interopservices using system.collections.specialized us...

讀寫ini檔案

using system using system.io using system.text using system.configuration using system.runtime.interopservices using system.collections.specialized us...