TypeLoader.cs 1.6 KB

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