Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to load all assemblies from within your /bin directory

Tags:

c#

assemblies

In a web application, I want to load all assemblies in the /bin directory.

Since this can be installed anywhere in the file system, I can't gaurantee a specific path where it is stored.

I want a List<> of Assembly assembly objects.

like image 293
mrblah Avatar asked Aug 17 '09 14:08

mrblah


People also ask

What is the method to load assembly given its file name and its path?

LoadFrom(String) Loads an assembly given its file name or path.

What is assembly load?

The assembly is loaded into the application domain of the caller. Load(String) Loads an assembly with the specified name. Load(AssemblyName) Loads an assembly given its AssemblyName.


2 Answers

Well, you can hack this together yourself with the following methods, initially use something like:

string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 

to get the path to your current assembly. Next, iterate over all DLL's in the path using the Directory.GetFiles method with a suitable filter. Your final code should look like:

List<Assembly> allAssemblies = new List<Assembly>(); string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);  foreach (string dll in Directory.GetFiles(path, "*.dll"))     allAssemblies.Add(Assembly.LoadFile(dll)); 

Please note that I haven't tested this so you may need to check that dll actually contains the full path (and concatenate path if it doesn't)

like image 152
Wolfwyrd Avatar answered Sep 27 '22 20:09

Wolfwyrd


To get the bin directory, string path = Assembly.GetExecutingAssembly().Location; does NOT always work (especially when the executing assembly has been placed in an ASP.NET temporary directory).

Instead, you should use string binPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin");

Further, you should probably take the FileLoadException and BadImageFormatException into consideration.

Here is my working function:

public static void LoadAllBinDirectoryAssemblies() {     string binPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin"); // note: don't use CurrentEntryAssembly or anything like that.      foreach (string dll in Directory.GetFiles(binPath, "*.dll", SearchOption.AllDirectories))     {     try     {                             Assembly loadedAssembly = Assembly.LoadFile(dll);     }     catch (FileLoadException loadEx)     { } // The Assembly has already been loaded.     catch (BadImageFormatException imgEx)     { } // If a BadImageFormatException exception is thrown, the file is not an assembly.      } // foreach dll } 
like image 29
Jason S Avatar answered Sep 27 '22 19:09

Jason S