CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Steve Hebert's Development Blog

Steve's Blog - From .Net to dotMath and everything in between.

Accessing a project-level file at runtime

Here's the code for accessing a physical file (i.e. jpg, gif, etc.) that is referenced in the solution. I run into this bit of code every once in a while but never frequently enough to remember it off the top of my head...

Stream stream=Assembly.GetExecutingAssembly().GetManifestResourceStream("[project].[path].[file]");



Comments

Geoff Appleby said:

Hey dude.

So, if I'm reading you right, if a physical file is referenced in the project and not just happens to be in the same folder, it's embedded in a resource?

I need to learn this bit, I think :)
# June 29, 2005 5:19 PM

Steve Hebert said:

I forgot one point... click on the file you want embedded in the exe/dll and change the Build Action property to "Embedded Resource". Once you do this, you'll be able to use the embedded file as shown above.
# June 29, 2005 8:30 PM

Sam said:

A quick tip: WinForms/Console and WebApps will give you perhaps unexpected results when calling .GetExecutingAssembly() or .GetCallingAssembly(), so I find it useful to use .GetAssembly(Type) instead.

This way it doesn't matter if a library is called from a Console or a WebApp, it'll just work if I specify a Type from the assembly I want a handle on.

Also, no matter how many times I see it, the path seems to always confuse me. If I can't seem to get a handle on a resource, .GetManifestResourceNames() will give me a nice string array I can step through with the debugger so I can just copy & paste the path.
# June 29, 2005 9:02 PM

Steve Hebert said:

Thanks Sam, those are great points.

I like the idea of using ResourceNames to see the string array since GetManifestResourceStream() only returns a null if the specified resource does not exist.
# June 29, 2005 9:38 PM
Check out Devlicio.us!

Our Sponsors

Free Tech Publications