tags:

views:

476

answers:

2

Hello,

How do I write an array of something into one Ident in an ini file and lately How do I read from it and store the value in an array?

This is how I'd like the ini to look like:

[TestSection]
val1 = 1,2,3,4,5,6,7

Problems I have:

  1. I don't know the functions I have to use
  2. The size is not static.It may be more than 7 values,it may be less.How do I check the length?
+9  A: 

You can do it like this,

uses inifiles

procedure ReadINIfile
var
  IniFile : TIniFile;
  MyList:TStringList;
begin
    MyList  := TStringList.Create();
    try 
        MyList.Add(IntToStr(1));
        MyList.Add(IntToStr(2));
        MyList.Add(IntToStr(3));


        IniFile := TIniFile.Create(ChangeFileExt(Application.ExeName,'.ini'));
        try               
            //write to the file 
            IniFile.WriteString('TestSection','Val1',MyList.commaText);

            //read from the file
            MyList.commaText  := IniFile.ReadString('TestSection','Val1','');


            //show results
            showMessage('Found ' + intToStr(MyList.count) + ' items ' 
                            + MyList.commaText);
        finally
            IniFile.Free;
        end;
    finally
        FreeAndNil(MyList);
   end;

end;

You will have to save and load the integers as a CSV string as there is no built in function to save arrays direct to ini files.

Re0sless
FYI, rogue spaces in your array will through it off.
Jim McKeeth
+9  A: 

You do not need length specifier. The delimiter clearly delimits the parts of the array.

if you have a section in INI file defined like this

[TestSection]
val1 = 1,2,3,4,5,6,7

then all you have to do is

procedure TForm1.ReadFromIniFile;
var
  I: Integer;
  SL: TStringList;
begin
  SL := TStringList.Create;
  try
    SL.StrictDelimiter := True;
    SL.CommaText := FINiFile.ReadString('TestSection', 'Val1', '');
    SetLength(MyArray, SL.Count);

    for I := 0 to SL.Count - 1 do
      MyArray[I] := StrToInt(Trim(SL[I]))
  finally
    SL.Free;
  end;
end;

procedure TForm1.WriteToIniFile;
var
  I: Integer;
  SL: TStringList;
begin
  SL := TStringList.Create;
  try
    SL.StrictDelimiter := True;

    for I := 0 to Length(MyArray) - 1 do
      SL.Add(IntToStr(MyArray[I]));

    FINiFile.WriteString('TestSection', 'Val1', SL.CommaText);
  finally
    SL.Free;
  end;
end;
Runner
heh, Re0sless was a little bit faster :)
Runner
I wish I could accept yours too.+1
John
no problem, glad to be of help :)
Runner