.NET6控制台程序报CS0234缺少System.Windows.Forms引用如何修复
问题描述
- 执行命令
dotnet new console -o MyApp -f net6.0创建了.NET 6控制台程序 - 修改Program.cs文件,写入如下测试代码:
global using System.Windows.Forms; System.Console.WriteLine("Primary screen resolution: " + SystemInformation.PrimaryMonitorSize); System.Console.WriteLine("Virtual size: " + SystemInformation.VirtualScreen); System.Console.WriteLine("Monitors count: " + SystemInformation.MonitorCount);
- 在项目路径
PS C:\Users\box\Desktop\dotnet\MyApp>下执行dotnet run时出现构建错误,报错内容:
C:\Users\box\Desktop\dotnet\MyApp\Program.cs(1,29): error CS0234: The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?) [C:\Users\box\Desktop\dotnet\MyApp\MyApp.csproj] The build failed. Fix the build errors and run again.
- 开发时使用系统自带记事本编写代码,已确认代码中使用的
SystemInformation类属于System.Windows.Forms命名空间、对应依赖为System.Windows.Forms.dll,需要解决依赖缺失导致的编译失败问题。
解决方法
报错的直接原因是普通.NET控制台项目默认不会引入Windows Forms相关的桌面组件依赖,按以下步骤修复即可:
- 打开项目目录下的
MyApp.csproj文件(用记事本就能直接打开编辑),将原有内容替换为以下配置:
*关键改动有两点:一是将目标框架修改为带<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0-windows</TargetFramework> <UseWindowsForms>true</UseWindowsForms> </PropertyGroup> </Project>-windows后缀的Windows专属版本,因为Windows Forms是Windows平台专属组件,不支持跨平台运行;二是添加<UseWindowsForms>true</UseWindowsForms>配置,编译时会自动引入Windows Forms相关的所有程序集,不需要手动单独添加dll引用。 - 保存csproj文件后,在项目目录下依次执行以下命令:
等待依赖还原完成后,程序就能正常编译运行,输出屏幕分辨率、虚拟屏幕尺寸、显示器数量等参数。dotnet restore dotnet run
- 补充说明:不需要额外安装特殊编辑工具,记事本完全可以满足代码编写需求,只要本地已经正确安装.NET 6 SDK就能完成所有操作,不需要安装Visual Studio这类重型IDE。
内容的提问来源于stack exchange,提问作者Ultra
相关产品推荐
相关产品推荐

