How to save and read an array from an INI file?

How to write an array of something into a single identifier in an ini file and recently How did I read it and save the value in the array?

This is how I would like to look like this:

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

I have problems:

  • I do not know what functions I should use
  • Size is not static.It can be more than 7 values, it can be less. How to check the length?
+3
source share
2 answers

You can do it as follows:

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 need to save and load the integers as a CSV string, since there is no built-in function to save arrays directly in ini files.

+10
source

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

INI,

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

, ,

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;
+12

Source: https://habr.com/ru/post/1714605/


All Articles