Ini files: DeleteKey leaves empty section
When an ini file contains a section with only one key (like MySection1
in
[MySection1]
MyKey1=MyValue1
[MySection2]
...
) calling DeleteKey
for that key leaves an empty section:
[MySection1]
[MySection2]
...
I'd prefer if that empty section would be removed too. Of course I can call something like
if not ini.SectionExists('MySection1') then
ini.EraseSection('MySection1');
after every call to DeleteKey
(or make an overridden TExtIniFile.DeleteKey
do that) but I hope there is an automatic way to make Windows or the VCL do that. Do you know any?
Update: I'm using a TIniFile descendant that solely adds some additional Read*/Write* methods.
Update: My test routine:
procedure TForm1.Button1Click(Sender: TObject);
var
ini: TMyIniFile;
begin
ini := TMyIniFile.Create(cIniFileName);
try
ini.WriteString('MySection1', 'MyKey1', 'MyValue1');
ini.DeleteKey('MySection1', 'MyKey1');
finally
ini.Free;
end;
Show;
end;
procedure TForm1.Show;
begin
if FileExists(cIniFileName) then
Memo1.Lines.L开发者_如何学GooadFromFile(cIniFileName)
else
Memo1.Lines.Clear;
end;
TMyIniFile
can be an alias for TIniFile
or a descendant of TMemIniFile
with an destructor calling UpdateFile
.
I don't think there is "automatic way to make Windows or the VCL do that". I believe that the reason is that "API" doesn't know that you don't intend to use that section anymore (ie if the API would delete the section after you delete the last key someone would complain that this is inefficient as they intend to add an key to that section later and so the section must be recreated). Also, one could argue that the existence of the empty section carries information too and thus that information would be lost in case of automatic deletion.
I don't believe that either TIniFile
or TMemIniFile
will operate the way you want. Therefore the possible solutions are:
- Override
DeleteKey
as you suggest. - Override
UpdateFile
and remove all empty sections at that point.
精彩评论