Reputation: 35532
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:
Upvotes: 3
Views: 13898
Reputation: 10886
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.
Upvotes: 12
Reputation: 6103
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;
Upvotes: 13