问题描述
经过 10 多个小时的研究后,我允许自己在此论坛上发布我的问题,但没有任何解决方案。 基本上,我正在使用以下目标框架编写我的第二个 C# 应用程序(仅限命令行):.NET Core 3.1
问题是从 Sytem.Windows.Forms 程序集使用 OpenFileDialog 时。这是代码,但这不是代码问题。
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);
在“调试模式”下运行代码时效果很好(Microsoft Visual Studio)。但是当在 Visual Studio Code 上使用“dotnet restore”+“dotnet run”,然后使用 .exe 时,它告诉我:
命名空间“System.Windows”中不存在“Form”。
现在,当我手动添加引用 windows.Forms.dll
(不必在以前的项目中也使用 openFileDialog 来实现相同的功能)时,它告诉我:
未将对象引用设置为对象的实例。
所以我真的很困惑。现在我决定回到我以前的项目,看看它是如何使用我从来不需要手动执行的“Windows.Forms”的。我看到它使用了不同的路径:“C:\Program Files\dotnet\packs\Microsoft.WindowsDesktop.App.Ref\3.1.0\ref\netcoreapp3.1\System.Windows.Forms.dll”。所以我敢肯定,两者都有相同的目标框架,所以它应该可以工作,但事实并非如此。它告诉我:
System.BadImageFormatException: 无法加载文件或程序集
有人对此有什么想法吗?
任何帮助将不胜感激。
解决方法
有一个技巧——当你想使用 Windows 窗体时,你必须在 dotnetcore3.1 的项目文件中启用它们。这是它对我有用的方式:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>Exe</OutputType>
<UseWindowsForms>true</UseWindowsForms>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>