Before I get started, I’d just like to point out that this snippet is not game development specific. It could be useful in any application.
Here we go then…
Lets say you have some asset, file, media, whatever that needs to be distributed with your application, and your application programatically loads it. You could just distribute it as a file in it’s own right, but you might like to consider embedding it in your exe.
Why?:
Convenience!!!
No need to copy this content to your Bin folder for runtime, debugging etc…
Minimise tampering.
What if it was your company’s logo, and people could tamper with the Image and change the branding of your application?
Or in the case of game development, you don’t really want your textures where cheaters can buggerize with them! You know, change the textures Alpha channel, so the entire texture is tranparent in the game.
Convinced? It’s very easy to do.
Add your content into your project.
In the files Properties change it to an Embedded Resource.
Now here’s a helper class for getting a Stream of the content.
using System; |
using System.Text; |
using System.Reflection; |
using System.IO; |
|
namespace MyProject.Helpers |
{ |
public class ResourceHelper |
{ |
/// <summary> |
/// Returns a stream for the named embedded resource. |
/// </summary> |
/// <param name="nameSpace">The namespace containing the embedded resource. Case sensitive!</param> |
/// <param name="name">The filename of the embedded resource. Case sensitive!</param> |
/// <returns></returns> |
public static Stream GetEmbeddedStream(string nameSpace, string name) |
{ |
Stream result = null; |
|
Assembly a = Assembly.GetExecutingAssembly(); |
string resourceName = String.Format("{0}.{1}", nameSpace, name); |
result = a.GetManifestResourceStream(resourceName); |
|
return result; |
} |
} |
} |
|
Simply call the GetEmbeddedStream from your code passing the nameSpace & the name of the desired file. (case sensitive)
e.g.
Stream myStream = ResourceHelper.GetEmbeddedStream("MyProject.Goodies.Images", "TheManWithTwoBrains.jpg"); |
Once you have a Stream you can use it with any class that lets you load from a stream.
That’s it! Enjoy.
Average Rating: 4.5 out of 5 based on 283 user reviews.