Reputation: 16845
I am trying to retrieve all defined types into a .NET assembly by using System.Reflection
in C#. First I load the assembly:
var assembly = Assembly.LoadFrom("C:\...\myassembly.dll");
Then I try to get all the TypeInfo
for the types in the assembly:
try {
var types = assembly.DefinedTypes;
}
catch(ReflectionTypeLoadException ex)
{
var errorMessage = new StringBuilder();
errorMessage.AppendLine($"Error loading defined types in assembly {this.assembly.FullName}. Found {ex.LoaderExceptions.Length} errors:");
foreach (var innerException in ex.LoaderExceptions)
{
errorMessage.AppendLine($"{innerException.GetType().Name} - {innerException.HResult}: {innerException.Message}");
}
throw new InvalidOperationException(errorMessage.ToString(), ex);
}
The failure I have is ReflectionTypeLoadException
and I get in ex.LoaderExceptions
a lot of exceptions like:
-2146233054: Could not load type 'MyType' from assembly 'myassembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the method '.ctor' has no implementation (no RVA)
I have found this question which deals about this same problem, one of the suggestions was to use:
var assembly = Assembly.ReflectionOnlyLoadFrom("C:\...\myassembly.dll");
Which seemed pretty logic. However it did not work.
My question is simple: how can I get all the TypeInfo
from the available types by ignoring errors on types that are not fully defined in the assembly or that lack implementation?
I know that ex.Types
will give me a list of types I can use from the exception, but that would give me a System.Type
not a System.Reflection.TypeInfo
. I want the latter as it has more information about the types which I need. The question I linked does not deal with this problem!
Upvotes: 2
Views: 410
Reputation: 4218
You can get the TypeInfo
from the Type
object by calling the IntrospectionExtensions.GetTypeInfo
extension method. So it should be as simple as this:
var typeInfo = ex.Types.Select(IntrospectionExtensions.GetTypeInfo).ToArray();
Upvotes: 2