brian4342
brian4342

Reputation: 1253

use reflection to search in DLLs c#

Currently I am using reflection to search my assemblies for classes that implement an interface, I then check the names of these classes to see that it matches the one that is been searched for.

My next task is to add to this code a way to search DLL files in the directory, my only hint is that I could use "System.Environment.CurrentDirectory". I also need to account for the fact that not all the DLLs contain .net assemblies.

Could anyone recommend where to start on this?

        IInstruction instruction = null;
        string currentDir = Environment.CurrentDirectory;

        var query = from type in Assembly.GetExecutingAssembly().GetTypes()
                    where type.IsClass && type.GetInterfaces().Contains(typeof(IInstruction))
                    select type;

        foreach (var item in query)
        {
            if (opcode.Equals(item.Name, StringComparison.InvariantCultureIgnoreCase))
            {
                instruction = Activator.CreateInstance(item) as IInstruction;
                return instruction;
            }
        }

opcode is the name of a class im searching for.

Upvotes: 4

Views: 4955

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 180867

Something like this should get you started, it will attempt to load all .dll files in the current directory and return all types they contain that have the short name contained in opcode;

private static IEnumerable<Type> GetMatchingTypes(string opcode)
{
    var files = Directory.GetFiles(Environment.CurrentDirectory, "*.dll");

    foreach (var file in files)
    {
        Type[] types;
        try
        {
            types = Assembly.LoadFrom(file).GetTypes();
        }
        catch
        {
            continue;  // Can't load as .NET assembly, so ignore
        }

        var interestingTypes =
            types.Where(t => t.IsClass &&
                             t.GetInterfaces().Contains(typeof (IInstruction)) &&
                             t.Name.Equals(opcode, StringComparison.InvariantCultureIgnoreCase));

        foreach (var type in interestingTypes)
            yield return type;
    }
}

Upvotes: 5

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

Use Assembly.LoadFile method on found dlls:

foreach (var dllPath in Directory.EnumerateFiles(Environment.CurrentDirectory, "*.dll"))
{
    try
    {
        var assembly = Assembly.LoadFile(dllPath);
        var types = assembly.GetTypes();
    }
    catch (System.BadImageFormatException ex)
    {
        // this is not an assembly
    }
}

Upvotes: 0

Related Questions