How to read data embedded in your program's resources
Why do it?
In a previous article we dealt with why and how to embed data from a file in your program's resources. If we do that we're going to want to extract it again.
How it's done
This article assumes that the data you embedded was in the RCDATA format. This is a user-defined data format so we also assume that you know how to decode the format.
Reading it back from the resource is very simple due to the TResourceStream class that ships with Delphi. You create a TResourceStream in one of two ways:
1var
2 RS: TResourceStream;
3begin
4
5 RS := TResourceStream.Create(
6 HInstance,
7 ResourceName,
8 RT_RCDATA);
9
10
11 RS := TResourceStream.CreateFromID(
12 HInstance,
13 ResourceID,
14 RT_RCDATA);
15end;
Listing 1
You now just use the stream to read the data as if it was coming from a file. You can't write to a TResourceStream as data embedded in an executable file is read only.
To copy your embedded file into another stream (say Stm of type TStream) you can use this code:
1Stm.CopyFrom(RS, RS.Size);
Listing 2
As an example, say we have a program that includes a resource file that contains an RCDATA resource which has a copy of a rich text file inside it. The program displays the embedded rich text in a rich edit component. This is the code we need:
1var
2 RS: TResourceStream;
3begin
4
5 RS := TResourceStream.CreateFromID(HInstance,
6 100, RT_RCDATA);
7 try
8
9 RichEdit1.Lines.LoadFromStream(RS);
10 finally
11
12 RS.Free;
13 end;
14end;
Listing 3
Demo Code
A demo program to accompany this article (and the related article) can be found in the delphidabbler/article-demos
Git repository on GitHub.
You can view the code in the article-02+03
sub-directory. Alternatively download a zip file containing all the available demos by going to the repository's landing page and clicking the Clone or download button and selecting Download ZIP.
The demo demonstrates what has been described here. It contains a pair of projects. The first is a program that embeds a supplied rich text file in a resource file. The second program includes the resource file and displays the rich text in a rich edit component.
This source code is merely a proof of concept and is intended only to illustrate this article. It is not designed for use in its current form in finished applications. The code is provided on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
The demo is open source. See the demo's LICENSE.md file for licensing details.
Feedback
I hope you found this article useful.
If you have any observations, comments, or have found any errors there are two places you can report them.
- For anything to do with the article content, but not the downloadable demo code, please use this website's Issues page on GitHub. Make sure you mention that the issue relates to "article #3".
- For bugs in the demo code see the
article-demo
project's README.md
file for details of how to report them.