How to Read an Embedded File in .NET

| | Comments (0)

So I was trying to figure out how to keep my wallpaper changer application a single-file executable, but easily include ChangeLog information that shows up in the about box. So I figured, hey, I'll make a change log and embed it as a resource into the executable. Then I can just load the resource up at runtime and dump its contents however I want. w00t. Well, this is a hard thing to figure out how to do when you're not too familiar with how things really work. So I asked Jake for a bit of help, which he graciously gave me. Unfortunately, he was going down the wrong path (though it would have worked, it was just very difficult). So I figured that there had to be an easier way, and there is. So here's the steps on how to embed a text file into an application so you can read it back in at runtime.

  1. Go to Project->Add Item and add your text file. Give it whatever name you'd like.
  2. Select the newly made file from the file browser, and change its Build Action to be Embedded Resource.
  3. Fill out the text file however you want to. I just put a bunch of lines for the ChangeLog, but you could put in things like your EULA, About text, etc.
  4. Now you're ready to access the file. I'll show you a few snippets of code to get a StreamReader to the file. First, add: [syntax] using System.Reflection; using System.IO; [/syntax] to the top of your file.
  5. Now, when you want to actually get the StreamReader, you just need to put in this code: [syntax] Assembly asm = Assembly.GetExecutingAssembly(); StreamReader reader = new StreamReader( asm.GetManifestResourceStream( "AppNamespace.FileName.FileExtension" ) ); [/syntax] And you now have a StreamReader for the text file that you embedded. Don't forget to add a call to reader.Close when you're done with it!

So, as you can see, this is pretty dang easy. I would suggest using this approach when adding files that you want to edit yourself, but you don't want to bother exposing for the user to be able to edit. It's quite easy to do, and it keeps your application very clean.

Leave a comment

Disclaimer

I'm currently an employee of REAL Software. My blog is mine. The opinions represented in this blog are mine as well and may not represent my employer's opinions. All original material is copyrighted and property of the author.

REALbasic® is a registered trademark of REAL Software, Inc. REAL SQL Server™ and Lingua™ are pending trademarks of REAL Software, Inc. All rights reserved.