DotNet core Reflection load assembly

Date: 2020-04-03
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace LoadClassInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_ReflectionOnlyAssemblyResolve;
            Assembly.ReflectionOnlyLoadFrom(@"C:\Program Files (x86)\Uniconta\Uniconta.Common.dll");
            Assembly assembly = Assembly.ReflectionOnlyLoadFrom(@"C:\Program Files (x86)\Uniconta\Uniconta.WindowsAPI.dll");

            var types = new List<Type>();
            Type t;

            t = assembly.GetType("Uniconta.ClientTools.DataModel.DebtorOfferClient");
            if (t != null)
                types.Add(t);

            t = assembly.GetType("Uniconta.ClientTools.DataModel.DebtorOfferLineClient");
            if (t != null)
                types.Add(t);

            t = assembly.GetType("Uniconta.ClientTools.DataModel.DebtorOrderClient");
            if (t != null)
                types.Add(t);

            t = assembly.GetType("Uniconta.ClientTools.DataModel.DebtorOrderLineClient");
            if (t != null)
                types.Add(t);

            var sb = new StringBuilder();
            foreach (var type in types)
            {
                var publicProps = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                sb.AppendLine($"public class {type.Name}");
                sb.AppendLine("{");
                foreach (var prop in publicProps)
                {
                    var propType = prop.PropertyType;
                    var propTypeName = prop.PropertyType.Name;
                    if (propType.GenericTypeArguments.Length > 0) {
                        propTypeName = $"{prop.PropertyType.Name}<{string.Join(",", propType.GenericTypeArguments.Select(gt => gt.Name))}>";
                    }
                    propTypeName = propTypeName.Replace("`1", "");
                    sb.AppendLine($"  public {propTypeName} {prop.Name};");
                }
                sb.AppendLine("}");
            }

            Console.WriteLine(sb.ToString());
        }

        static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
        {
            try
            {
                return Assembly.ReflectionOnlyLoad(args.Name);
            }
            catch (FileNotFoundException)
            {
                try
                {
                    var path = Path.GetDirectoryName(args.RequestingAssembly.Location);
                    path = Path.Combine(path, args.Name);
                    return Assembly.ReflectionOnlyLoadFrom(path);
                }
                catch (Exception) { }
            }
            catch (Exception) { }
            return null;
        }
    }
}
36240cookie-checkDotNet core Reflection load assembly