开发者

How do I assign an INI section to a record in delphi 7

开发者 https://www.devze.com 2023-03-15 04:27 出处:网络
I\'m sorry I\'m not being clear...lets try again I have a record type : MyRecord = Record Name: string; Age: integer;

I'm sorry I'm not being clear...lets try again

I have a record type :

MyRecord = Record
   Name: string;
   Age: integer;
   Height: integer;
   several more fields....

and an INI file with:

[PEOPLE]
Name=Maxine
Age=30
maybe one or two other key/value pairs

All I want to do is load the record with the data from the INI file.

I have the data from the INI in a TStringLi开发者_Go百科st I want to be able to loop through the TStringList and assign/update only the Record Fields with key value pairs in the TStringList.

Charles


So you have an INI file with the content

[PEOPLE]
Name=Maxine
Age=30

and want to load it into a record defined by

type
  TMyRecord = record
    Name: string;
    Age: integer;
  end;

? That is very easy. Just add IniFiles to the uses clause of your unit, and then do

var
  MyRecord: TMyRecord;

procedure TForm1.Button1Click(Sender: TObject);
begin
  with TIniFile.Create(FileName) do
    try
      MyRecord.Name := ReadString('PEOPLE', 'Name', '');
      MyRecord.Age := ReadInteger('PEOPLE', 'Age', 0);
    finally
      Free;
    end;
end;

Of course, the MyRecord variable need not be a global variable. It can also be a local variable or a field in a class. But that all depends on your exact situation, naturally.

A Simple Generalisation

A slightly more interesting situation is if your INI files contains several people, like

[PERSON1]
Name=Andreas
Age=23

[PERSON2]
Name=David
Age=40

[PERSON3]
Name=Marjan
Age=49

...

and you want to load it into an array of TMyRecord records, then you can do

var
  Records: array of TMyRecord;

procedure TForm4.FormCreate(Sender: TObject);
var
  Sections: TStringList;
  i: TIniFile;
begin
  with TIniFile.Create(FileName) do
    try
      Sections := TStringList.Create;
      try
        ReadSections(Sections);
        SetLength(Records, Sections.Count);
        for i := 0 to Sections.Count - 1 do
        begin
          Records[i].Name := ReadString(Sections[i], 'Name', '');
          Records[i].Age := ReadInteger(Sections[i], 'Age', 0);
        end;
      finally
        Sections.Free;
      end;

    finally
      Free;
    end;
end;


If you have the INI section in a string list you can just use the Values[] property:

String list contents

Name=Maxine
Age=30

Code to read into record

MyRecord.Name := StringList.Values['Name']
MyRecord.Age = StrToInt(StringList.Values['Age'])

Naturally you would want to handle errors one way or another, but this the the basic idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消