Troubleshooting Reflection Exceptions in .Net

While troubleshooting the unit test case, I have encountered a reflection error that I was not sure where went wrong. There are multiple solutions people mentioned, add DLL to copy to local and other solutions. In my case, I have tried all but did not work. The system was showing generic error messages like below. So, I wanted to trouble actual reflection errors by throwing exceptions catching them.

System.Reflection.ReflectionTypeLoadException
HResult=0x80131602
Message=Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Source=
StackTrace:

Here code to troble to reflection errors

try
{
// add your reflection error here
}
catch (ReflectionTypeLoadException ex)
{
StringBuilder sb = new StringBuilder();
foreach (Exception exSub in ex.LoaderExceptions)
{
sb.AppendLine(exSub.Message);
FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
if (exFileNotFound != null)
{
if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
{
sb.AppendLine("Fusion Log:");
sb.AppendLine(exFileNotFound.FusionLog);
}
}
sb.AppendLine();
}
string errorMessage = sb.ToString();
//Display or log the error based on your application.
}

In my case, error was

Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=5.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.

Added dll reference and resolved the issue 🙂

Credits: https://forums.asp.net/t/2116695.aspx?Unable+to+load+one+or+more+of+the+requested+types+Retrieve+the+LoaderExceptions+property+for+more+information

Leave a Reply

Your email address will not be published.