.net 8 add System.Windows.PresentationCore dll and using System.Windows.Media namespace
1.add reference,C:\Program Files\dotnet\packs\Microsoft.WindowsDesktop.App.Ref\8.0.11\ref\net8.0\PresentationCore.dll
2.Source code
using System; using System.Windows; using System.Windows.Media; namespace ConsoleApp19 { internal class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); string str = Guid.NewGuid().ToString(); PrintTextFontsizeWidth(str, "Arial", 120); } static void PrintTextFontsizeWidth(string str, string fontFamilyName, int fontSize) { FormattedText formattedText = new FormattedText( str, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(fontFamilyName), fontSize, Brushes.Black, 1.25); Console.WriteLine($"{str}\nWidth:{formattedText.Width}\nHeight:{formattedText.Height}"); } } }
3.Run and throw exception
System.BadImageFormatException HResult=0x80131058 Message=Could not load file or assembly 'PresentationCore, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Reference assemblies cannot be loaded for execution. (0x80131058) Source=ConsoleApp19 StackTrace: at ConsoleApp19.Program.PrintTextFontsizeWidth(String str, String fontFamilyName, Int32 fontSize) in D:\C\ConsoleApp19\ConsoleApp19\Program.cs:line 26 at ConsoleApp19.Program.Main(String[] args) in D:\C\ConsoleApp19\ConsoleApp19\Program.cs:line 13 Inner Exception 1: BadImageFormatException: Cannot load a reference assembly for execution.
4.Edit csproj file
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <UseWPF>true</UseWPF> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <Reference Include="PresentationCore"> <HintPath>C:\Program Files\dotnet\packs\Microsoft.WindowsDesktop.App.Ref\8.0.11\ref\net8.0\PresentationCore.dll</HintPath> </Reference> </ItemGroup> </Project>
5.Run and errors
The target platform must be set to Windows (usually by including '-windows' in the TargetFramework property) when using Windows Forms or WPF, or referencing projects or packages that do so.
6.Edit csproj file again,and the ultimate edition.
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0-windows</TargetFramework> <UseWPF>true</UseWPF> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <Reference Include="PresentationCore"> <HintPath>C:\Program Files\dotnet\packs\Microsoft.WindowsDesktop.App.Ref\8.0.11\ref\net8.0\PresentationCore.dll</HintPath> </Reference> </ItemGroup> </Project>
7.Run
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
2017-02-04 Linq