TypeLoader.cs 1.7 KB

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