You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用csc命令编译CS文件后执行失败:无法加载System.Runtime程序集

解决编译生成的EXE无法加载System.Runtime程序集的问题

你遇到的核心问题是直接使用Roslyn的csc.exe编译时,错误引用了仅用于编译的.NET Core引用程序集(Reference Assemblies),同时未明确指定目标框架版本,导致运行时无法找到正确的System.Runtime等依赖的实现文件。Microsoft.NETCore.App.Ref包里的程序集是编译时用的"存根",不包含实际运行代码,不能用于运行时加载。


方案一:使用dotnet命令行工具编译(推荐)

dotnet CLI会自动处理框架依赖、程序集引用和运行时绑定,比手动调用csc更可靠,步骤如下:

  1. 在临时目录创建一个简单的.csproj文件(比如TempScript.csproj):
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <SelfContained>false</SelfContained> <!-- 若要生成不依赖系统.NET运行时的独立EXE,设为true并指定RuntimeIdentifier -->
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Data.SqlClient" Version="5.1.5" /> <!-- 匹配你使用的版本 -->
  </ItemGroup>
  <ItemGroup>
    <Compile Include="TestScript.cs" />
  </ItemGroup>
</Project>
  1. 修改MainProgram.cs中的编译逻辑,调用dotnet build:
Process process = new Process();
process.StartInfo.FileName = "dotnet";
process.StartInfo.Arguments = "build TempScript.csproj -o ."; // 将输出文件放到当前目录
process.StartInfo.WorkingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); // 可指定临时目录避免文件混乱
process.Start();
process.WaitForExit();

// 运行生成的EXE
string exePath = Path.Combine(process.StartInfo.WorkingDirectory, "TempScript.exe");
Process.Start(exePath);
return 0;

如果需要生成独立可执行文件(不依赖目标机器的.NET运行时),修改.csproj中的SelfContained为true,添加RuntimeIdentifier(比如win-x64),然后用dotnet publish代替dotnet build:

dotnet publish TempScript.csproj -c Release -r win-x64 --self-contained true -o .

方案二:修正csc编译参数(不推荐,手动维护依赖复杂)

如果坚持用csc,需要引用运行时程序集而非引用程序集,同时指定目标框架版本:

  1. 找到.NET Core 8.0的运行时程序集路径,通常在C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11(和你的Ref包版本一致)
  2. 修改csc的参数,替换引用路径,并添加目标框架参数:
process.StartInfo.Arguments = @"/out:""TestScript.exe"" /target:exe /framework:net8.0 " +
@"/reference:""Microsoft.Data.SqlClient.dll"" " +
@"/reference:""C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Data.Common.dll"" " +
@"/reference:""C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Runtime.dll"" " +
@"/reference:""C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Console.dll"" " +
@"/reference:""C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\mscorlib.dll"" " +
@"""TestScript.cs""";

注意:手动维护这些引用非常繁琐,后续框架更新或依赖变化都需要手动调整,因此优先推荐方案一。

内容的提问来源于stack exchange,提问作者Adrian Przemysław Drozdowski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 19:41:05