我正在尝试使用官方微软
文档了解更多关于
System.Reflection
的信息。具体来说,我正在尝试运行以下示例:
// Loads an assembly using its file name.
Assembly a = Assembly.LoadFrom("MyExe.exe");
// Gets the type names from the assembly.
Type[] types2 = a.GetTypes();
foreach (Type t in types2)
{
Console.WriteLine(t.FullName);
}
所以我使用
dotnet new console -o=customconsole
制作了一个新的控制台应用程序。然后我从项目文件中删除了 ImplicitUsings
(因为我不喜欢那样),并提出了以下代码:
using System;
using System.Reflection;
namespace get_type_from_assembly
{
internal class Program
{
static void Main(string[] args)
{
// load assembly using full file name
Assembly a = Assembly.LoadFrom("C:\\Users\\bobmarley\\desktop\\temp\\csharp-reflection\\get-type-from-assembly\\bin\\Debug\\net6.0\\console-custom.exe");
// get type names from assembly
Type[] types2 = a.GetTypes();
foreach (Type t in types2)
{
Console.WriteLine(t.FullName);
}
}
}
}
然后我尝试使用
dotnet run --project=customconsole
运行生成的可执行文件。我收到以下运行时错误:
Unhandled exception. System.BadImageFormatException: Bad IL format. The format of the file 'C:\Users\bobmarley\desktop\temp\csharp-reflection\get-type-from-assembly\bin\Debug\net6.0\console-custom.exe' is invalid.
at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly)
at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
at System.Reflection.Assembly.LoadFrom(String assemblyFile)
at get_type_from_assembly.Program.Main(String[] args) in C:\Users\bobmarley\desktop\temp\csharp-reflection\get-type-from-assembly\Program.cs:line 11
make: *** [Makefile:5: run] Error 1
我不确定为什么会发生这种情况,因为我检查过,可执行文件确实存在于指定的路径中。这里发生了什么以及我该如何解决它?
一个可能的原因是您的项目和加载的程序集针对不同的平台,即 x86 与 x64,根据我的经验,这是
BadImageFormatException
的常见原因。另一个可能的原因是一个针对 .net core,而另一个针对 .net Framework。
动态加载程序集需要它与您的项目兼容。如果您想读取任意程序集,您可能需要一些工具来直接从 CIL 代码中提取您想要的任何信息,而无需实际加载它。
FWIW 将 .NET Framework 项目升级到 .NET Core 后,我开始遇到相同的错误。不过,我可以通过使用同一目录中相应的 DLL 文件来解决这个问题。