Search code examples
.net-coref#windows-forms-core

I get an exception when I instantiate a WebBrowser Control in my F# app


I am trying to instantiate a WebBrowser control within my F# application:

open System;;
open System.Net.Http;;
open System.Windows.Forms;;
...
let browser =
    new WebBrowser(ScriptErrorsSuppressed = true,
                   Dock = DockStyle.Fill,
                   DocumentText = fsharpOrg.Result)

But I get this exception:

System.IO.FileLoadException: **Could not load file or assembly 'System.Drawing.Common**, Version=6.0.0.0,...

I am using dotnet sdk version 6.0.100. I have searched for answers or similar problems in forums and documentation, but I have not found something that can lead me to the fix. Any insight we'll be appreciated.


Solution

  • Don't use #r in code, use it only in script files.

    Error occurs because runtime tries to find System.Drawing.Common inside output folder, e.g. bin/debug/net6.0/, but not in C:/Program Files/dotnet/shared/...

    To fix error you should:

    1. create project file,
    2. add <UseWindowsForms>true</UseWindowsForms> into <PropertyGroup>, so project will look like this:
    <Project Sdk="Microsoft.Net.SDK">
      <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <OutputType>winexe<OutputType>
        <UseWindowsForms>true</UseWindowsForms> <!-- all magic in this line -->
      </PropertyGroup>
    
      <ItemGroup>
        <Compile Include="Program.fs" />
      </ItemGroup>
    </Project>
    
    1. MSBuild will resolve all necessary references and you will be able to run program