TypeLoader.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. namespace BepInEx.Bootstrap
  6. {
  7. public static class TypeLoader
  8. {
  9. /// <summary>
  10. /// Loads a list of types from a directory containing assemblies, that derive from a base type.
  11. /// </summary>
  12. /// <typeparam name="T">The specfiic base type to search for.</typeparam>
  13. /// <param name="directory">The directory to search for assemblies.</param>
  14. /// <returns>Returns a list of found derivative types.</returns>
  15. public static IEnumerable<Type> LoadTypes<T>(string directory)
  16. {
  17. List<Type> types = new List<Type>();
  18. Type pluginType = typeof(T);
  19. foreach (string dll in Directory.GetFiles(Path.GetFullPath(directory), "*.dll"))
  20. {
  21. try
  22. {
  23. AssemblyName an = AssemblyName.GetAssemblyName(dll);
  24. Assembly assembly = Assembly.Load(an);
  25. foreach (Type type in assembly.GetTypes())
  26. {
  27. if (!type.IsInterface && !type.IsAbstract && type.BaseType == pluginType)
  28. types.Add(type);
  29. }
  30. }
  31. catch (BadImageFormatException) { } //unmanaged DLL
  32. catch (ReflectionTypeLoadException)
  33. {
  34. BepInLogger.Log($"ERROR! Could not load \"{Path.GetFileName(dll)}\" as a plugin!");
  35. }
  36. }
  37. return types;
  38. }
  39. }
  40. }