2009-08-07 84 views
3

如何在Ini文件中将一组东西写入一个Ident中,最近如何从中读取并将值存储在数组中?如何从INI文件中存储和读取数组?

这是我怎么想ini中的样子:

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

问题,我有:

  1. 我不知道我要使用
  2. 大小的功能不是静态的。它可能超过7个值,可能更少。我如何检查长度?

回答

10

你可以像这样做,

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; 

你将不得不整数保存和加载为CSV字符串,因为没有内置的功能,以节省阵列直接到INI文件。

+1

仅供参考,您的阵列中的流氓空间将通过它关闭。 – 2009-08-07 16:43:38

12

您不需要长度说明符。分隔符清楚地界定了数组的各个部分。

如果你在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; 
+0

heh,Re0sless有点快:) – Runner 2009-08-07 13:19:38

+0

我希望我也能接受你的。+ 1 – 2009-08-07 14:01:28

+0

没问题,很高兴能帮上忙:) – Runner 2009-08-07 14:19:52