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
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.
User contributions licensed under CC BY-SA 3.0