Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a binary resource in a C# application

Tags:

.net

resources

I'm trying to store an empty Access database (.mdb) as a resource in my application. I then want to write it out the file system and populate it with table definitions, etc. The problem I'm having in Visual Studio 2005 and my C# application is with not being able to access the resource stored in the same assembly (which I would have thought would be accessible by default). Here's my code:

byte[] abytResource;
System.Reflection.Assembly objAssembly = System.Reflection.Assembly.GetExecutingAssembly();
objStream = objAssembly.GetManifestResourceStream("empty.mdb");
abytResource = new Byte[objStream.Length];
objStream.Read(abytResource, 0, (int)objStream.Length);
objFileStream = new FileStream(newDatabasePathWithName, FileMode.Create);
objFileStream.Write(abytResource, 0, (int)objStream.Length);
objFileStream.Close();

GetManifestResourceStream returns NULL and according to the documentation that's because the resource must be private (because even if it doesn't exist a non-NULL value is returned). So my question is this:

How do i make my resource accessible to my own application? I already added it to the project and marked it as "Embedded Resource", by the way.

Thanks!

like image 481
Karim Avatar asked Apr 07 '09 14:04

Karim


1 Answers

You need to prefix the "empty.mdb" with the default namespace of the assembly. Something like:

objStream = objAssembly.GetManifestResourceStream("My.Namespace.empty.mdb");
like image 53
David M Avatar answered Jan 02 '23 07:01

David M