Search code examples
c#powershellmsbuildiconscsc

How to change the icon of a C# program without using an IDE?


I have a single C# file (Source code.cs) that I compile with a PowerShell file (Compile.ps1) using Microsoft's compiler:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe -out:"Program.exe" -target:winexe "Source code.cs"

It creates the executable Program.exe.

How can I change its icon? The icon of the executable which appears in the taskbar when running the program. I have Icon.ico in the same folder.

I only found this page asking the same question with a solution that I didn't quite understood.

Note that I'm asking specifically how to do it without any IDE.


Solution

  • After a while of trial and error I managed to get it working with the Settings.csproj file as:

    <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <Target Name="Compile">
        <Csc OutputAssembly="Program.exe" Sources="Source code.cs" TargetType="WinExe" Win32Icon="Icon.ico"/>
      </Target>
    </Project>
    

    I don't understand why trying to use PropertyGroup would get ignored but then I found I could use Csc's parameters instead.

    It can then be compiled with csc.exe:

    C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe "Settings.csproj"
    

    Or MSBuild.exe:

    C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe "Settings.csproj"
    

    Which is good in case I need to change other project properties but for now a more simple solution that I found from the console output of running the above is that I can simply use the -win32icon compiler option:

    C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe -out:"Program.exe" -target:winexe -win32icon:Icon.ico "Source code.cs"