0

Unhandled Exception: System.IO.FileLoadException: The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)

I am getting an exception from C# in a simple program consisting of two classes, Program.cs and AnotherClass.cs. I want to use the static Type.GetType method in Program.cs to get AnotherClass as a class when given as a string for a more complex program. When I use the following code

class Program
{
    static void Main(string[] args)
    {
        Assembly a = Assembly.GetExecutingAssembly();
        //Console.WriteLine(a.FullName);
        Type t = Type.GetType($"SmallTestingSimulator.{a.FullName}.AnotherClass");
        Console.WriteLine(t.Name);
    }
}

and an empty class in a different file but same namespace

class AnotherClass {

}

I get the error. How do I go about using Type.GetType() for another class in this project? Without using the assembly, it gives a NullReferenceException.

Related Questions

Type.GetType("namespace.a.b.ClassName") returns null

Marvin
  • 853
  • 2
  • 14
  • 38

1 Answers1

1

Let's drill through the reflection that happens and figure it out:

Console.WriteLine(a.FullName);

writes

ProjectAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

To figure out what we need to send into Type.GetType(), we can just spit out the FullName of the type we're trying to get:

Console.WriteLine(typeof(AnotherClass).FullName);

and that should output something like:

SmallTestingSimulator.AnotherClass

Then, your call to get the type could just run

var t = Type.GetType($"SmallTestingSimulator.AnotherClass");

This should work in most cases, unless you're doing something goofy with namespaces/assemblies.

eouw0o83hf
  • 9,438
  • 5
  • 53
  • 75
  • This doesn't matter if "AnotherClass" is in a folder, correct? – Marvin Jul 24 '19 at 21:48
  • So what you're saying is, the assembly qualifier doesn't matter to return the Class as a Type object? – Marvin Jul 24 '19 at 22:32
  • Correct - the assembly qualifier is unnecessary there, and folder doesn't matter. The only thing that would make a difference is if `AnotherClass` is also in another namespace, in which case that would need to be specified (e.g. `$"SmallTestingSimulator.SubNamespace.AnotherClass"`). – eouw0o83hf Jul 25 '19 at 00:37