-1

I have a text file with key value pairs like this

user1|password1
user2|password2
user3|password3

In delphi 10 I use this function to get the key value

function getKeyByName(fileName, key: string) : string;
var
  dataFile : TStringList;
begin
  Result := 'Not Found';
  dataFile := TStringList.Create;
  dataFile.LoadFromFile(fileName);
  dataFile.NameValueSeparator := '|';
  if dataFile.Values[key] <> '' then
    Result := dataFile.Values[key];
  dataFile.Free;
end;

For now every thing is worked fine.

I try to use this function with delphi 5, but the property (NameValueSeparator) is not exists.

If I change the separator to (=) and the function to:

function getKeyByName(fileName, key: string) : string;
var
  dataFile : TStringList;
begin
  Result := 'Not Found';
  dataFile := TStringList.Create;
  dataFile.LoadFromFile(fileName);
  if dataFile.Values[key] <> '' then
    Result := dataFile.Values[key];
  dataFile.Free;
end;

I can get the result, but the separator in my text file is (|).

What should I do to set the separator char (|) for the list?

Thanks for help.

Rober.Ya
  • 65
  • 3
  • 12

1 Answers1

2

Delphi 5 does not have the NameValueSeparator property, so you will have to parse the individual strings manually, eg:

function getKeyByName(fileName, key: string) : string;
var
  dataFile : TStringList;
  i, j: Integer;
  s: string;
begin
  Result := 'Not Found';
  dataFile := TStringList.Create;
  try
    dataFile.LoadFromFile(fileName);
    for i := 0 to dataFile.Count-1 do
    begin
      s := dataFile[i];
      j := Pos('|', s);
      if j = 0 then Continue;
      if Copy(s, 1, j-1) <> key then Continue;
      s := Copy(s, j+1, MaxInt);
      if s <> '' then Result := s;
      Break;
    end;
  finally
    dataFile.Free;
  end;
end;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770