Embed Resources into your .Net Projects

Worrying about file paths, locations, availability, and security of your project’s resource can be a real pain.  Fortunately, you can easily embed resources into your project’s DLL and reference them with ease from your code.  Here’s an example of how to reference an embedded XSD:

First, to embed the resource, right click on the file and choose Properties.  Next, switch the Build Action on the file to Embedded Resource. Now, when you compile your project, your resource will be compiled into the DLL with the default namespace of the project/folder location of the file within your project, e.g. if your default namespace is example.project and you put the resource into a subfolder called Resources, you would reference the file as example.project.Resources.MySchema.xsd.

To reference your embedded resource from within your code, you use reflection:

Assembly.GetExecutingAssembly().GetManifestResourceStream(“example.project.MySchema.xsd”)

which returns a Stream.  Finally, just use the XmlSchema.Read method to slurp in the stream and voila, you have your schema.

This entry was posted in C#, Visual Studio. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *