Utility.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. namespace BepInEx.NetLauncher
  6. {
  7. /// <summary>
  8. /// Generic helper properties and methods.
  9. /// </summary>
  10. public static class LocalUtility
  11. {
  12. /// <summary>
  13. /// Try to resolve and load the given assembly DLL.
  14. /// </summary>
  15. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  16. /// <param name="directory">Directory to search the assembly from.</param>
  17. /// <param name="assembly">The loaded assembly.</param>
  18. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  19. private static bool TryResolveDllAssembly<T>(AssemblyName assemblyName, string directory, Func<string, T> loader, out T assembly) where T : class
  20. {
  21. assembly = null;
  22. var potentialDirectories = new List<string> { directory };
  23. potentialDirectories.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories));
  24. foreach (string subDirectory in potentialDirectories)
  25. {
  26. string path = Path.Combine(subDirectory, $"{assemblyName.Name}.dll");
  27. if (!File.Exists(path))
  28. continue;
  29. try
  30. {
  31. assembly = loader(path);
  32. }
  33. catch (Exception)
  34. {
  35. continue;
  36. }
  37. return true;
  38. }
  39. return false;
  40. }
  41. /// <summary>
  42. /// Try to resolve and load the given assembly DLL.
  43. /// </summary>
  44. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  45. /// <param name="directory">Directory to search the assembly from.</param>
  46. /// <param name="assembly">The loaded assembly.</param>
  47. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  48. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly)
  49. {
  50. return TryResolveDllAssembly(assemblyName, directory, Assembly.LoadFile, out assembly);
  51. }
  52. }
  53. }