jeudi 9 juin 2022

Runtime error with a very basic reflection example in C#

I'm trying to learn a bit more about System.Reflection using the official microsoft docs. Specifically I'm trying to run the following example:

// 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);
}

So I made a new console app using dotnet new console -o=customconsole. I then removed ImplicitUsings from my project file (because I don't like that), and came up with the following code:

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);
            }

        }
    }
}

Then I tried to run the generated executable using dotnet run --project=customconsole. I got the following runtime error:

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

I'm not sure why this occurs, because I checked and the executable does exist in the specified path. What is happening here and how can I fix it?





Aucun commentaire:

Enregistrer un commentaire