不使用部分读取值

时间:2012-02-19 20:58:31

标签: delphi delphi-7 ini

如何在不使用章节的情况下从INI文件中读取值? 所以不是普通的文件:

[section]
name=value

它会导致:

name=value

4 个答案:

答案 0 :(得分:9)

我不会把它称为INI文件。无论如何,为此,TStringList类非常适合。

考虑文件animals.txt

dog=Sally
rat=Fiona
cat=Linus

考虑一下这段代码:

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;

答案 1 :(得分:3)

有一个很好的教程over here。例如,如果iniFileTIniFile的实例,则可以使用空的节说明符调用iniFile.ReadString方法。

答案 2 :(得分:0)

这是一个迟到的答案,但这里是我为我的项目编写的一些代码:

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;

答案 3 :(得分:-1)

我认为这个问题确实需要更多信息。 通常人们会提出与他们认为需要做什么相关的问题而不是询问与他们实际想要完成的事情有关的问题。

为什么需要这样做而不是使用读取ini条目的常规方法? 如果这些是现有的ini文件,那么您应该使用Tinifile.ReadSections将部分名称读入字符串列表,然后使用Tinifile.ReadSectionValues遍历该列表以读取所有部分名称/值对。

您是在阅读现有的INI文件,还是阅读和编写自己的文件? 如果这些是你自己的文件,那么Andreas在上面有一个很好的答案。

相关问题