Home > Mobile >  Delphi 10.4 Community Edition - inifile.ReadString does not return default value when it should ...?
Delphi 10.4 Community Edition - inifile.ReadString does not return default value when it should ...?

Time:11-08

Am I not seeing the forest for the trees?

Delphi returns '' on inifile.ReadString() instead of the supplied default parameter. According to the help, it should return the default when either section, key, or value are missing.

I am pretty sure I have used this a number of times before without any issues before.

unit Unit1;

interface

uses
  Classes, System.SysUtils, Inifiles, Dialogs;

implementation

const
  DRIVE_SECTION = 'USB_Drives';
  DRIVE_LETTER  = 'DriveLetter';
  INI_NAME      = 'c:\temp\test.ini';

//--------------------------------------------------------
procedure CreateDefaultInifile(const IniName: TFileName);
var
  slist: TStringList;
begin
  slist := TStringList.Create;
  try
    slist.Add('['   DRIVE_SECTION   ']');
    slist.Add(DRIVE_LETTER   ' = ');
    //
    slist.SaveToFile(IniName);
  finally
    slist.Free;
  end;
end;

begin
  if not FileExists(INI_NAME) then
    CreateDefaultInifile(INI_NAME);
  // now we have an inifile with a key that has no value
  var ini := TIniFile.Create(INI_NAME);
  Showmessage(ini.ReadString(DRIVE_SECTION, DRIVE_LETTER, 'Missing_Value'));
  // according to Delphi's help, the default ('Missing_Value' in this case) should be returned if no value is assigned!
  ini.Free;
end.

end.

CodePudding user response:

Well, your INI file looks like this:

[USB_Drives]
DriveLetter = 

Clearly, there is a key named DriveLetter, and its value is the empty string.

Had the file instead been

[USB_Drives]
DriverFrogness = 

you would indeed have received your Missing_Value, because then there isn't a DriveLetter key.

You apparently are under the impression that an empty string counts as a missing value. However, according to the documentation for the GetPrivateProfileString function, which the RTL's TIniFile.ReadString() is a thin wrapper around:

[in] lpDefault

A default string. If the lpKeyName key cannot be found in the initialization file, GetPrivateProfileString copies the default string to the lpReturnedString buffer.

CodePudding user response:

The documentation for TIniFile.ReadString() (and for TMemIniFile.ReadString(), for that matter) is misleading. Specifically, the clause:

Default is the string value to return if the:

  • ...
  • Data value for the key is not assigned.

is wrong, and needs to be removed. The Default value is returned only if the specified Section or Key is not found. The value of the Key has no effect whatsoever on whether the Default is returned or not.

I have now filed a bug report with Embarcadero about this:

RSP-39946: Docs for TIniFile.ReadString() and TMemIniFile.ReadString() are wrong.

  • Related