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

C#加载System.Private.CoreLib.dll时遇FileNotFoundException异常求助(文件实际存在)

C#加载System.Private.CoreLib.dll时遇FileNotFoundException异常求助(文件实际存在)

嘿,我完全懂你这种明明文件就在眼前却报错找不到的抓狂感!咱们来好好捋一捋这个问题——你用这段代码加载核心库:

Assembly assembly = Assembly.LoadFrom("System.Private.CoreLib.dll");

结果抛出了:

Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'C:\Users\erikw\source\repos\DictMain\DictMain\bin\Debug\net9.0\System.Private.CoreLib.dll'. The system cannot find the file specified.

但你通过dir命令明明确认文件就在应用目录里:

C:\Users\erikw\source\repos\DictMain\DictMain\bin\Debug\net9.0>dir
 Volume in drive C is Windows-SSD
 Volume Serial Number is 745E-1B48

 Directory of C:\Users\erikw\source\repos\DictMain\DictMain\bin\Debug\net9.0

07/18/2025  03:28 PM    <DIR>          .
07/12/2025  07:21 PM    <DIR>          ..
07/18/2025  03:15 PM               416 DictMain.deps.json
07/18/2025  03:28 PM             5,120 DictMain.dll
07/18/2025  03:28 PM           155,136 DictMain.exe
07/18/2025  03:28 PM            10,836 DictMain.pdb
07/18/2025  03:15 PM               268 DictMain.runtimeconfig.json
07/12/2025  08:31 PM               303 dllKey.txt
07/18/2025  03:12 PM         1,601,536 System.Private.CoreLib.dll
               7 File(s)      1,773,615 bytes
               2 Dir(s)  3,804,758,093,824 bytes free

问题根源

其实这个矛盾的核心在于:System.Private.CoreLib.dll不是普通的第三方程序集,它是.NET Core/.NET 5+运行时的核心私有组件。.NET的程序集加载机制会优先从共享框架(或自包含部署的运行时专属目录)加载它,哪怕你把文件复制到了应用文件夹,运行时也不会走你指定的路径,而是沿用内置的加载逻辑,这就导致了“文件存在但加载失败”的情况。

解决办法(按推荐程度排序)

  • 优先用内置方式获取程序集引用:如果你只是想拿到这个核心库的Assembly对象,根本不需要手动加载!你的应用本身就依赖它,直接通过任意一个核心类型就能获取:

    // 通过object类型获取,object是核心库的基础类型
    Assembly coreLibAssembly = typeof(object).Assembly;
    // 或者用string类型也可以
    Assembly coreLibAssembly = typeof(string).Assembly;
    

    这种方式既安全又不会有加载问题,是最推荐的方案。

  • 特殊场景下的手动加载:如果你确实有必须手动加载的需求,可以尝试用AssemblyLoadContext绕过默认加载逻辑,指定绝对路径加载:

    string coreLibPath = @"C:\Users\erikw\source\repos\DictMain\DictMain\bin\Debug\net9.0\System.Private.CoreLib.dll";
    Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(coreLibPath);
    

    ⚠️ 注意:这种方式可能引发运行时兼容性问题,因为这个库和当前应用的.NET版本强绑定,随意加载容易导致奇怪的运行时错误,非必要不建议这么做。

  • 检查部署模式:如果你的项目是框架依赖部署,应用目录里的System.Private.CoreLib.dll可能只是个“标记文件”而非完整库(不过从你的dir输出看文件大小正常,这条可以作为辅助排查)。如果改成自包含部署,运行时会把核心库完整打包到应用目录,加载成功率会稍高,但依然不推荐手动加载。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 11:34:38