Loading Assemblies From Any Directory

1/7/2010

There are times on this site where I lie to you. Not that often, but when it does it's because I want to show a bit of code in a follow up posting. In this case, I lied to you when I said there isn't an easy way to load an assembly that is not in either the GAC or the bin directory of an app. The truth of the matter is that you can load any assembly (although I'm always iffy loading one that isn't in the GAC or came with the app in the bin). Anyway, in my new project I needed the ability to do this. In fact I needed the ability to load all assemblies in a specific directory. To make things easier I created a function to help me out:

   1: /// <summary>
   2: /// Gets a list of assemblies from a directory
   3: /// </summary>
   4: /// <param name="Directory">The directory to search in</param>
   5: /// <returns>List of assemblies in the directory</returns>
   6: public static System.Collections.Generic.List<Assembly> GetAssembliesFromDirectory(string Directory)
   7: {
   8:     System.Collections.Generic.List<Assembly> ReturnList = new System.Collections.Generic.List<Assembly>();
   9:     System.Collections.Generic.List<FileInfo> Files = FileManager.FileList(Directory);
  10:     foreach (FileInfo File in Files)
  11:     {
  12:         if (File.Extension.Equals(".dll", StringComparison.CurrentCultureIgnoreCase))
  13:         {
  14:             ReturnList.Add(Assembly.LoadFile(File.FullName));
  15:         }
  16:     }
  17:     return ReturnList;
  18: }

For those that find this page through Google or something, FileManager is a helper class from my utility library. All it does is gets all files from a specific directory and returns them in a list. But that's all there is to it: get file names, make sure they're a DLL, and use the Assembly.LoadFile function to load the assembly. Anyway, I hope this helps someone out. So give it a try, leave feedback, and happy coding.



Comments