I would like to add an ini file to my delphi project as a resource file.
I know where you go to add a file as a resource file:
Project > Resources and Images > Add
But once thats done what else do I need to do to be able to read from the file? I haven't used resource files before.
Is there any documentation on the process?
Thanks,
The built-in INI file classes in the RTL, providing in the System.IniFiles unit, require the INI file to be a disk file. So you could extract the resource to disk and read it from there.
If you don't like the idea of that then you could write your own INI file parser that operated on a stream rather than a file. You could use the code of TMemIniFile to guide you. Copy that code and replace LoadValues with code to read from a stream rather than a file. Or if you look hard enough then you may well find a third party INI parser that operates on streams.
If you are prepared to consider other formats then you might use JSON rather than INI. The built-in JSON parser does not require the input data to reside on disk. They can operate on in-memory strings, which sounds rather more convenient.
This above text is in fact nonsense. Thank you to Remy for pointing that out. You can use TMemIniFile and its SetStrings method to parse INI content that does not reside on disk. It goes like this:
TStringList, and assign the string variable to the Text property of the string list.TMemIniFile.SetStrings on the TMemIniFile passing the string list.Or:
TResourceStream object to read that resource.TStringList object.LoadFromStream on the string list passing the resource stream.TMemIniFile.SetStrings on the TMemIniFile passing the string list.Having said all of this, it seems odd that you would choose to do this at all. Wouldn't it be simpler just to hard code the configuration information in a unit, as a series of constants?
Using the "Resources and Images" dialog, add the .ini file to the project as a RCDATA resource type. Then, you can load it at runtime like this:
uses
..., Classes, IniFiles;
var
Ini: TMemIniFile;
List: TStringList;
Strm: TResourceStream;
begin
Ini := TMemIniFile.Create;
try
List := TStringList.Create;
try
Strm := TResourceStream.Create(HInstance, 'ResourceIDHere', RT_RCDATA);
try
List.LoadFromStream(Strm);
finally
Strm.Free;
end;
Ini.SetStrings(List);
finally
List.Free;
end;
// use Ini as needed...
finally
Ini.Free;
end;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With