tags:

views:

532

answers:

2

Hi,

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.

+1  A: 

You can do it like this, but you should probably not load everything into the current appdomain like this, since assemblies might contain harmful code.

public IEnumerable<Assembly> LoadAssemblies()
{
    DirectoryInfo directory = new DirectoryInfo(@"c:\mybinfolder");
    FileInfo[] files = directory.GetFiles("*.dll", SearchOption.TopDirectoryOnly);

    foreach (FileInfo file in files)
    {
        // Load the file into the application domain.
        AssemblyName assemblyName = AssemblyName.GetAssemblyName(file.FullName);
        Assembly assembly = AppDomain.CurrentDomain.Load(assemblyName);
        yield return assembly;
    } 

    yield break;
}

EDIT: I have not tested the code (no access to Visual Studio at this computer), but I hope that you get the idea.

Patrik
+6  A: 

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

string path = 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 = 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)

Wolfwyrd
You'll probably also want to add a check to ensure you don't add the Assembly that you're actually running as well :)
Wolfwyrd
The `path` variable contains the directory filename, it needs to be shortened with `Path.GetDirectoryName(path)`
ck