tags:

views:

42

answers:

3

Given that I am generating an exe application with AssemblyBuilder, how do I set an icon to it?

I think I should be using

System.Reflection.Emit.AssemblyBuilder.DefineUnmanagedResource

Is there an example how to do it?


http://msdn.microsoft.com/en-us/library/aa380599(VS.85).aspx

A: 

You need to set up an ResourceManager by defining an IResourceWriter and write to it, then read in the icon as bytes and set it, according to this documentation from MSDN, I guess the code would look something like this, as I have not done this before, judging by the code sample, after you save the assembly, add the unmanaged resource and name it as 'app.ico':

// Defines a standalone managed resource for this assembly.
IResourceWriter myResourceWriter = myAssembly.DefineResource("myResourceIcon",
         "myResourceIcon.ico", "MyAssemblyResource.resources", 
         ResourceAttributes.Public);
myResourceWriter.AddResource("app.ico", "Testing for the added resource");

myAssembly.Save(myAssembly.GetName().Name + ".dll");

// Defines an unmanaged resource file for this assembly.
bool bSuccess = false;
byte[] iconB = null;
using (System.IO.FileStream fStream = new FileStream("icon.ico", FileMode.Open, FileAccess.Read)){
    iconB = new byte[(int)fStream.Length];
    int nRead = fStream.Read(out iconB, 0, iconB.Length);
    if (nRead == iconB.Length) bSuccess = true;
}
if (bSuccess){
    myAssembly.DefineUnmanagedResource(iconB);
}
tommieb75
+1  A: 

Yes, you'll need DefineUnmanagedResource(). The file you pass must be in the .RES file format. That requires the rc.exe Windows SDK tool. To create one, start by creating a text file named test.rc with this content:

 100 ICON test.ico

Where test.ico is the name of a file that contains the icon. Start the Visual Studio Command Prompt and use this command

 rc test.rc

That creates a test.res file. Pass its path to DefineUnmanagedResource(), your final .exe contains the icon resource.

Note that this is not verify practical, the target machine probably won't have the Windows SDK installed and you cannot redistribute rc.exe. But you could distribute the .res file.

Hans Passant
I wonder if it were possible to create a template "res" file and then swap the icon in it?
zproxy
The .res file format is not documented. You could figure out the offset of the binary .ico data but you'll run into trouble when the replacement .ico is not the same size.
Hans Passant
+1  A: 

You could also change the icon after saving the EXE using the Win32 resource APIs BeginUpdateResource, UpdateResource and EndUpdateResource. See http://stackoverflow.com/questions/1797461/change-wpf-assembly-icon-from-code (which isn't WPF specific).

El Zorko