Rider下Avalonia 项目启动问题完整解决方案

问题描述

症状 1:编译时找不到 CommunityToolkit 命名空间

错误信息:

复制代码
ViewModelBase.cs(1,7): Error CS0246 : 未能找到类型或命名空间名"CommunityToolkit"(是否缺少 using 指令或程序集引用?)
ViewModelBase.cs(5,30): Error CS0246 : 未能找到类型或命名空间名"ObservableObject"(是否缺少 using 指令或程序集引用?)

症状 2:运行时找不到 SkiaSharp 程序集

错误信息:

复制代码
Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'SkiaSharp, Version=2.88.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756'. 系统找不到指定的文件。
File name: 'SkiaSharp, Version=2.88.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756'
   at Avalonia.Skia.PlatformRenderInterface..ctor(Nullable`1 maxResourceBytes)
   at Avalonia.Skia.SkiaPlatform.Initialize(SkiaOptions options)

问题原因分析

原因 1:NuGet 包未正确还原

  • CommunityToolkit.Mvvm 包虽然在项目文件中引用,但实际程序集未正确还原到本地
  • 编译器找不到对应的 DLL 文件

原因 2:NuGet 缓存损坏

  • SkiaSharp 2.88.9 包在 NuGet 缓存中损坏或不完整
  • 缺少托管的 SkiaSharp.dll 文件
  • 构建过程未能将 DLL 复制到输出目录

原因 3:IDE 文件锁定

  • Rider IDE 在后台锁定某些 DLL 文件
  • 导致无法清理和重新下载包文件

完整解决方案

步骤 1:关闭 IDE

关闭所有可能锁定项目文件的 IDE:

  • JetBrains Rider
  • Visual Studio
  • Visual Studio Code

⚠️ 重要提示:必须完全关闭 IDE,否则某些 DLL 文件会被锁定,导致清理失败。

步骤 2:清理项目文件

打开 PowerShell 或命令提示符,进入项目目录:

powershell 复制代码
cd D:\your-project-path\AvaloniaApplication2

删除 bin 和 obj 目录:

powershell 复制代码
Remove-Item -Recurse -Force obj, bin -ErrorAction SilentlyContinue

或者在 Linux/macOS 上:

bash 复制代码
rm -rf obj bin

步骤 3:清除 NuGet 缓存

清除所有 NuGet 缓存:

powershell 复制代码
dotnet nuget locals all --clear

预期输出:

复制代码
正在清除 NuGet HTTP 缓存: C:\Users\[用户名]\AppData\Local\NuGet\v3-cache
正在清除 NuGet 全局包文件夹: C:\Users\[用户名]\.nuget\packages\
正在清除 NuGet 临时缓存: C:\Users\[用户名]\AppData\Local\Temp\NuGetScratch
正在清除 NuGet 插件缓存: C:\Users\[用户名]\AppData\Local\NuGet\plugins-cache
本地资源已清除。

步骤 4:还原 NuGet 包

重新下载所有依赖包:

powershell 复制代码
dotnet restore

预期输出:

复制代码
正在确定要还原的项目...
已还原 D:\your-project-path\AvaloniaApplication2\AvaloniaApplication2.csproj (用时 X.XX 秒)。

📝 注意:首次还原可能需要较长时间(10-30 秒),取决于网络速度。

步骤 5:清理并重新构建

执行清理:

powershell 复制代码
dotnet clean

构建项目:

powershell 复制代码
dotnet build

预期输出:

复制代码
已成功生成。
    0 个警告
    0 个错误

步骤 6:验证 SkiaSharp.dll

检查关键文件是否存在:

powershell 复制代码
ls bin\Debug\net8.0\SkiaSharp.dll

应该看到文件信息:

复制代码
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         2024/11/7     21:55         437808 SkiaSharp.dll

步骤 7:运行项目

启动应用程序:

powershell 复制代码
dotnet run

成功标志:

  • 没有错误信息输出
  • Avalonia 窗口成功打开
  • 显示默认的 "Welcome to Avalonia!" 界面

项目配置参考

推荐的 .csproj 配置(Avalonia 11.3.6)

xml 复制代码
<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
        <Nullable>enable</Nullable>
        <BuiltInComInteropSupport>true</BuiltInComInteropSupport>
        <ApplicationManifest>app.manifest</ApplicationManifest>
        <AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
    </PropertyGroup>

    <ItemGroup>
        <Folder Include="Models\" />
        <AvaloniaResource Include="Assets\**" />
    </ItemGroup>

    <ItemGroup>
        <PackageReference Include="Avalonia" Version="11.3.6"/>
        <PackageReference Include="Avalonia.Desktop" Version="11.3.6"/>
        <PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.6"/>
        <PackageReference Include="Avalonia.Fonts.Inter" Version="11.3.6"/>
        <PackageReference Include="Avalonia.Diagnostics" Version="11.3.6">
            <IncludeAssets Condition="'$(Configuration)' != 'Debug'">None</IncludeAssets>
            <PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
        </PackageReference>
        <PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0"/>
    </ItemGroup>
</Project>

快速修复脚本

Windows PowerShell 一键修复脚本

创建文件 fix-avalonia.ps1

powershell 复制代码
# Avalonia 项目快速修复脚本
# 设置控制台编码为 UTF-8,避免中文乱码
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
chcp 65001 > $null

Write-Host "=== Avalonia 项目修复工具 ===" -ForegroundColor Cyan
Write-Host ""

# 检查是否在项目根目录
if (-not (Test-Path "*.csproj")) {
    Write-Host "错误: 请在项目根目录运行此脚本!" -ForegroundColor Red
    exit 1
}

Write-Host "步骤 1/6: 设置 UTF-8 编码..." -ForegroundColor Yellow
Write-Host "✓ 完成" -ForegroundColor Green

Write-Host "步骤 2/6: 清理项目文件..." -ForegroundColor Yellow
Remove-Item -Recurse -Force obj, bin -ErrorAction SilentlyContinue
Write-Host "✓ 完成" -ForegroundColor Green

Write-Host "步骤 3/6: 清除 NuGet 缓存..." -ForegroundColor Yellow
dotnet nuget locals all --clear
Write-Host "✓ 完成" -ForegroundColor Green

Write-Host "步骤 4/6: 还原 NuGet 包..." -ForegroundColor Yellow
dotnet restore
Write-Host "✓ 完成" -ForegroundColor Green

Write-Host "步骤 5/6: 清理项目..." -ForegroundColor Yellow
dotnet clean
Write-Host "✓ 完成" -ForegroundColor Green

Write-Host "步骤 6/6: 构建项目..." -ForegroundColor Yellow
dotnet build

if ($LASTEXITCODE -eq 0) {
    Write-Host ""
    Write-Host "=== 修复完成!===" -ForegroundColor Green
    Write-Host ""
    Write-Host "验证关键文件..." -ForegroundColor Cyan
    
    if (Test-Path "bin\Debug\net8.0\SkiaSharp.dll") {
        Write-Host "✓ SkiaSharp.dll 存在" -ForegroundColor Green
    } else {
        Write-Host "✗ SkiaSharp.dll 缺失" -ForegroundColor Red
    }
    
    Write-Host ""
    Write-Host "运行项目: dotnet run" -ForegroundColor Cyan
} else {
    Write-Host ""
    Write-Host "=== 构建失败,请检查错误信息 ===" -ForegroundColor Red
}

使用方法:

powershell 复制代码
# 在项目根目录执行
.\fix-avalonia.ps1

Linux/macOS Bash 修复脚本

创建文件 fix-avalonia.sh

bash 复制代码
#!/bin/bash

# Avalonia 项目快速修复脚本
echo "=== Avalonia 项目修复工具 ==="
echo ""

# 检查是否在项目根目录
if ! ls *.csproj &> /dev/null; then
    echo "错误: 请在项目根目录运行此脚本!"
    exit 1
fi

echo "步骤 1/5: 清理项目文件..."
rm -rf obj bin
echo "✓ 完成"

echo "步骤 2/5: 清除 NuGet 缓存..."
dotnet nuget locals all --clear
echo "✓ 完成"

echo "步骤 3/5: 还原 NuGet 包..."
dotnet restore
echo "✓ 完成"

echo "步骤 4/5: 清理项目..."
dotnet clean
echo "✓ 完成"

echo "步骤 5/5: 构建项目..."
dotnet build

if [ $? -eq 0 ]; then
    echo ""
    echo "=== 修复完成!==="
    echo ""
    echo "验证关键文件..."
    
    if [ -f "bin/Debug/net8.0/SkiaSharp.dll" ]; then
        echo "✓ SkiaSharp.dll 存在"
    else
        echo "✗ SkiaSharp.dll 缺失"
    fi
    
    echo ""
    echo "运行项目: dotnet run"
else
    echo ""
    echo "=== 构建失败,请检查错误信息 ==="
fi

使用方法:

bash 复制代码
# 添加执行权限
chmod +x fix-avalonia.sh

# 在项目根目录执行
./fix-avalonia.sh

常见问题排查

Q1: 清除缓存时提示 "未能删除" 错误

问题:

复制代码
error: 未能删除"C:\Users\...\Avalonia.Build.Tasks.dll"。

解决方法:

  1. 确保已完全关闭 Rider/Visual Studio
  2. 检查任务管理器中是否有相关进程
  3. 重启计算机后重试

Q2: 还原包时提示 "Access to the path is denied"

问题:

复制代码
error : Access to the path 'Avalonia.Build.Tasks.dll' is denied.

解决方法:

  1. 关闭所有 IDE
  2. 以管理员身份运行 PowerShell
  3. 重新执行清理和还原步骤

Q3: 构建成功但运行时仍然找不到 SkiaSharp

可能原因:

  • 输出目录中的 DLL 文件不完整
  • 使用了不兼容的 Avalonia 版本

解决方法:

powershell 复制代码
# 方案 1: 使用 publish 命令
dotnet publish -c Debug

# 方案 2: 手动复制 SkiaSharp.dll
Copy-Item "$env:USERPROFILE\.nuget\packages\skiasharp\2.88.9\lib\net6.0\SkiaSharp.dll" "bin\Debug\net8.0\"

Q4: 警告 NU1701 - SkiaSharp.NativeAssets 兼容性

警告信息:

复制代码
warning NU1701: Package 'SkiaSharp.NativeAssets.Win32 2.88.9' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework 'net8.0'.

说明:

  • 这是正常警告,不影响项目运行
  • SkiaSharp 的本机资产包使用旧框架版本是预期行为
  • 可以安全忽略此警告

Q5: 构建输出中文乱码

问题描述:

在 Windows 系统中,使用 Rider 或 PowerShell 构建项目时,控制台输出的中文显示为乱码:

复制代码
閫傜敤浜?.NET MSBuild 鐗堟湰 17.11.41+18f1ecf82
鐢熸垚鍚姩鏃堕棿涓?2025/10/13 14:19:42銆?
鑺傜偣 1 涓婄殑椤圭洰...

原因分析:

Windows PowerShell 默认使用 GBK/GB2312 编码,而 .NET MSBuild 输出使用 UTF-8 编码,导致编码不匹配。

临时解决方案(当前会话):

在执行构建命令前,设置 PowerShell 编码:

powershell 复制代码
# 设置输出编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 设置代码页为 UTF-8 (65001)
chcp 65001

# 然后执行构建
dotnet build

永久解决方案 - 方法 1:修改 PowerShell 配置文件

  1. 打开 PowerShell 配置文件:
powershell 复制代码
# 检查配置文件是否存在
Test-Path $PROFILE

# 如果不存在,创建配置文件
if (!(Test-Path $PROFILE)) {
    New-Item -Path $PROFILE -ItemType File -Force
}

# 编辑配置文件
notepad $PROFILE
  1. 在配置文件中添加以下内容:
powershell 复制代码
# 设置 PowerShell 输出编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

# 设置代码页为 UTF-8
chcp 65001 > $null
  1. 保存文件并重启 PowerShell

永久解决方案 - 方法 2:设置系统区域

  1. 打开 控制面板时钟和区域区域
  2. 点击 管理 标签
  3. 点击 更改系统区域设置
  4. 勾选 Beta: 使用 Unicode UTF-8 提供全球语言支持
  5. 重启计算机

⚠️ 注意:方法 2 会影响整个系统,可能导致某些旧程序显示异常,建议优先使用方法 1。

Rider IDE 解决方案:

在 Rider 中设置终端编码:

  1. FileSettings (或 Ctrl + Alt + S)

  2. ToolsTerminal

  3. Shell path 中添加启动参数:

    powershell.exe -NoExit -Command "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; chcp 65001"

或者使用 PowerShell Core (pwsh):

复制代码
pwsh.exe -NoExit -Command "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8"

验证解决方案:

设置后重新构建,应该看到正常的中文输出:

复制代码
正在确定要还原的项目...
所有项目均是最新的,无法还原。
AvaloniaApplication2 -> D:\...\AvaloniaApplication2.dll

已成功生成。
    0 个警告
    0 个错误

快速验证脚本:

powershell 复制代码
# 创建测试文件 test-encoding.ps1
@"
Write-Host "测试中文输出" -ForegroundColor Cyan
Write-Host "Test Chinese Output" -ForegroundColor Green
dotnet --version
"@ | Out-File -Encoding UTF8 test-encoding.ps1

# 执行测试
.\test-encoding.ps1

预防措施

1. 版本锁定

在 Directory.Build.props 中锁定版本:

xml 复制代码
<Project>
    <ItemGroup>
        <PackageReference Update="Avalonia" Version="11.3.6" />
        <PackageReference Update="Avalonia.Desktop" Version="11.3.6" />
    </ItemGroup>
</Project>

2. 使用 nuget.config

创建 nuget.config 配置清晰的包源:

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
</configuration>

3. 定期清理

添加到项目维护计划:

powershell 复制代码
# 每月执行一次
dotnet nuget locals all --clear
dotnet restore
dotnet build

4. 使用 .gitignore

确保不提交这些目录到版本控制:

gitignore 复制代码
bin/
obj/
.vs/
.idea/
*.user
*.suo

版本兼容性说明

Avalonia 11.3.x 系列

版本 .NET 目标 SkiaSharp 版本 状态
11.3.6 net6.0, net8.0 2.88.9 ✅ 推荐
11.3.7 net6.0, net8.0 2.88.9 ✅ 最新
11.2.2 net6.0, net8.0 2.88.7 ✅ 稳定

依赖包版本推荐

xml 复制代码
<PackageReference Include="Avalonia" Version="11.3.6"/>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0"/>

相关资源

官方文档

社区支持

总结

核心步骤回顾

  1. ✅ 关闭所有 IDE
  2. ✅ 删除 binobj 目录
  3. ✅ 清除 NuGet 缓存:dotnet nuget locals all --clear
  4. ✅ 还原包:dotnet restore
  5. ✅ 清理:dotnet clean
  6. ✅ 构建:dotnet build
  7. ✅ 验证 SkiaSharp.dll 存在
  8. ✅ 运行:dotnet run

问题根源

大多数 Avalonia 项目启动问题都源于:

  • 🔴 NuGet 缓存损坏
  • 🔴 IDE 文件锁定
  • 🔴 包未正确还原

解决关键

遵循 "清理 → 还原 → 构建" 的标准流程,确保环境干净,问题通常都能解决。


相关推荐
bemyrunningdog4 小时前
IntelliJ IDEA合并分支到master全攻略
大数据·elasticsearch·intellij-idea
相与还16 小时前
IDEA和GIT实现cherry pick拣选部分变更到新分支
git·elasticsearch·intellij-idea
Chan1621 小时前
流量安全优化:基于 Sentinel 实现网站流量控制和熔断
java·spring boot·安全·sentinel·intellij-idea·进程
一勺菠萝丶2 天前
[特殊字符] 芋道项目中的参数校验机制详解:以 AppProductActivityListReqVO 为例
intellij-idea
小蕾Java2 天前
Java 开发工具,最新2025 IDEA 使用,保姆级教程
java·开发语言·intellij-idea
刘登辉2 天前
idea使用联网缓存的pom进行离线开发
java·ide·intellij-idea·离线开发
摆烂且佛系2 天前
IDEA Maven 仓库配置优先级
github·maven·intellij-idea
瑶山2 天前
社区版Idea怎么创建Spring Boot项目?Selected Java version 17 is not supported. 问题解决
java·spring boot·intellij-idea·创建项目
Deryck_德瑞克2 天前
IDEA编译时报错OOM的解决方案
java·ide·intellij-idea