Vico Lays
Vico Lays

Reputation: 63

Windows.Forms assembly issue C# (.NET Core 3.1)

I allow myself to post my issue on this forum after 10+ hours of research without any solutions. Basically, I'm coding my second C# app (command line only) with the following target framework : .NET Core 3.1

The issue is when using OpenFileDialog from Sytem.Windows.Forms assembly. Here is the code, but it's not a code issue.

var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
    do
    {
        Console.Write(" Upload: \n");
        Thread.Sleep(500);
        openFileDialog.Title = "Upload";
        openFileDialog.DefaultExt = "txt";
        openFileDialog.Filter = "Text files|*.txt";
        openFileDialog.RestoreDirectory = true;
        openFileDialog.ShowDialog();
        filePath = openFileDialog.FileName;
    } while (!File.Exists(filePath));
}
myList= new List<string>(File.ReadAllLines(filePath));
LoadList(filePath);

When running the code in "Debug mode" it works well (Microsoft Visual Studio). But when using "dotnet restore" + "dotnet run" on Visual Studio Code, and then using the .exe, it's telling me that :

'Form' does not exist in the namespace 'System.Windows'.

Now when I add the reference manually windows.Forms.dll (did not have to do it on previous project that also use a openFileDialog for the same function), it's telling me that:

Object reference not set to an instance of an object.

So I'm really confused. Now I've decided to come back to my previous project and see how it uses the 'Windows.Forms' that I never had to impelment manually. I saw that it uses a different path : "C:\Program Files\dotnet\packs\Microsoft.WindowsDesktop.App.Ref\3.1.0\ref\netcoreapp3.1\System.Windows.Forms.dll". So I'm sure, both have the same target framework, so it should work, but it does not. It's telling me that :

System.BadImageFormatException: Could not load file or assembly

Does anyone have an idea about that?

Any help would be much appreciate.

Upvotes: 0

Views: 925

Answers (1)

Tom Placek
Tom Placek

Reputation: 11

There is a trick - when you want to use Windows Forms you have to make them enabled in project file in dotnetcore3.1. Here is way it works for me:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
   <PropertyGroup>
     <OutputType>Exe</OutputType>
     <UseWindowsForms>true</UseWindowsForms>
     <TargetFramework>netcoreapp3.1</TargetFramework>
   </PropertyGroup>
 </Project>

Upvotes: 1

Related Questions