Little Helper
Little Helper

Reputation: 2456

Reading value without using sections

How do I read value from INI file without using sections?
So instead of normal file:

[section]
name=value

it would result in this:

name=value

Upvotes: 4

Views: 3367

Answers (4)

Adriaan
Adriaan

Reputation: 806

This is a late answer but here is some code I wrote for my project:

function GetPropertyValue(aFile, Key: string): string;
var
  properties: TStringList;
begin
  properties := TStringList.Create;
  try
    properties.LoadFromFile(aFile);
    Result := properties.Values[key];
  finally
    properties.free;
  end;
end;

procedure SetPropertyValue(aFile, Key, Value: string);
var
  I: Integer;
  properties: TStringList;
  found: Boolean;
begin
  found := False;
  properties := TStringList.Create;
  try
    properties.LoadFromFile(aFile);
    for I := 0 to properties.Count -1 do
    begin
      if properties.Names[I] = Key then
      begin
        properties[I] := Key + '=' + Value;
        found := True;
        Break
      end;
    end;

    if not found then
    begin
      properties.Add(Key + '=' + Value);
    end;
  finally
    properties.SaveToFile(aFile);
    properties.free;
  end;
end;

Upvotes: 0

MikeD
MikeD

Reputation: 637

I think the question really needs more information. Often people will ask questions relating to what they think they need to do instead of asking questions related to what they are actually trying to accomplish.

Why do you need to do this instead of using the normal methods of reading the ini entries? If these are existing ini files, then you should use the Tinifile.ReadSections to read the section names into a stringlist and then iterate through that list using Tinifile.ReadSectionValues to read all the section name/values pairs.

Are you reading existing INI files, or reading and writing your own files? If these are your own files, then Andreas has a good answer above.

Upvotes: -1

Andreas Rejbrand
Andreas Rejbrand

Reputation: 109003

I wouldn't call it an INI file, then. Anyhow, for this the TStringList class fits perfectly.

Consider the file animals.txt:

dog=Sally
rat=Fiona
cat=Linus

And consider this code:

procedure TForm1.Button1Click(Sender: TObject);
begin
  with TStringList.Create do
    try
      LoadFromFile('C:\Users\Andreas Rejbrand\Desktop\animals.txt');
      ShowMessage(Values['dog']);
    finally
      Free;
    end;
end;

Upvotes: 9

ruhleder
ruhleder

Reputation: 334

There's a nice tutorial over here. For example, if iniFile is an instance of TIniFile, you can call the iniFile.ReadString method with an empty section specifier.

Upvotes: 2

Related Questions