Linking data files with your executable in .NET

Tamás Polgár
Developer rants
Published in
2 min readApr 3, 2024

Sometimes you want your data files to be embedded into your .exe file at build time. It’s been possible since Mark Zbikowski left his initials in the first executable, and of course, it’s still possible today.

In my use case, I had a couple of SQL queries to go with my application. This isn’t something I’d like to load from external text files, as they could be easily modified. Into the executable they go! Not only text files, but images, audio files and everything else can be linked the same way, but a text file is perhaps the easiest and best demonstration.

First, click your project in Solution Explorer, and select Properties.

Find the Resources tab. There is a small dropdown in the upper left corner, where you can select Files.

Now just drag your file into the window, and bam, you have your file in the project! In the Properties tab of Solution Explorer, you can view and change some really straightforward properties.

And there it is! Your data is now linked with the executable. Here is how you can access it. All you need is the name of the resource:

string resource = Properties.Resources.myResource;

If you want to refer to it with a dynamic string value, here’s a little trickery to make it safe:

string res = "myResource";

string contents = (string)typeof(Properties.Resources)
.GetProperty(resourceName, BindingFlags.NonPublic | BindingFlags.Static)
?.GetValue(null, null);

This will return the contents of the file as a string, or null if it’s not found.

--

--