If the Dll is a .NET assembly, you can call Assembly.GetManifestResourceStream
, like so:
public static Bitmap getBitmapFromAssemblyPath(string assemblyPath, string resourceId) {
Assembly assemb = Assembly.LoadFrom(assemblyPath);
Stream stream = assemb.GetManifestResourceStream(resourceId);
Bitmap bmp = new Bitmap(stream);
return bmp;
}
If it is a native dll (not an assembly), you will have to use Interop instead. You have a solution here, and could be summarized as follows:
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags);
[DllImport("kernel32.dll")]
static extern IntPtr FindResource(IntPtr hModule, int lpID, string lpType);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr LoadResource(IntPtr hModule, IntPtr hResInfo);
[DllImport("kernel32.dll", SetLastError = true)]
static extern uint SizeofResource(IntPtr hModule, IntPtr hResInfo);
[DllImport("kernel32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool FreeLibrary(IntPtr hModule);
static const int LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
public static Bitmap getImageFromNativeDll(string dllPath, string resourceName, int resourceId) {
Bitmap bmp = null;
IntPtr dllHandle = LoadLibraryEx(dllPath, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE);
IntPtr resourceHandle = FindResource(dllHandle, resourceId, resourceName);
uint resourceSize = SizeofResource(dllHandle, resourceHandle);
IntPtr resourceUnmanagedBytesPtr = LoadResource(dllHandle, resourceHandle);
byte[] resourceManagedBytes = new byte[resourceSize];
Marshal.Copy(resourceUnmanagedBytesPtr, resourceManagedBytes, 0, (int)resourceSize);
using (MemoryStream m = new MemoryStream(resourceManagedBytes)) {
bmp = (Bitmap)Bitmap.FromStream(m);
}
FreeLibrary(dllHandle);
return bmp;
}
No error handling was added, this is not production-ready code.
NOTE: Should you need an Icon, you can use the Icon constructor that receives a stream:
using (MemoryStream m = new MemoryStream(resourceManagedBytes)) {
bmp = (Icon)new Icon(m);
}
And you should change the return type accordingly.