Search code examples
c#.net-corebitmapsystem.drawing

System.Drawing.Common not working on Windows


I'm trying to run a simple C# Application on windows 11. I'm using the System.Drawing to edit a png file, but this error is occuring.

System.PlatformNotSupportedException: 'System.Drawing.Common is not supported on this platform.'

After a bit of research, turns out System.Drawing is only supported on windows.. but I am using windows.. Perhaps it's because I'm using windows 11?

Furthermore, adding

AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true);

Didn't seem to fix this issue either

The error is thrown on this line of code:

Bitmap bmp = new Bitmap(Bitmap.FromFile(file));

Solution

  • You must build your project for windows. You do this by adding -windows to your current Target Framework Moniker (TFM) in the project file:

      <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>net7.0-windows</TargetFramework>
        ...
      </PropertyGroup>
    

    This tells the compiler that you will be running your application exclusively on windows.

    If you are using winforms, also add

        <UseWindowsForms>true</UseWindowsForms>