tags:

views:

2304

answers:

4

I'm completely new to loading in libraries like this, but here's where I stand:

I have a homemade DLL file it's about as simple as it gets, the class itself and a method. In the home program that loads this library, I have:

Assembly testDLL = Assembly.LoadFile("C:\\dll\\test.dll");

From here, I'm kind of stuck. As far as I know, it's loading it correctly because it gives me errors when I change the name.

What do I do from here? How exactly do I load the class & methods within it?

Thanks.

+2  A: 

If this is a managed (.NET) DLL, I think you simply need to add a reference to the DLL in your project by right clicking "References" in the Solution Explorer and choosing "Add Reference." Go to browse and select your DLL. Once this is done, all you should have to do is add a "using" statement that corresponds to the namespace of the code that's in the DLL.

Lunchy
If you downvote an answer, please leave a brief comment explaining why. It's a courtesy thing.
Robert Harvey
If it was downvoted, someone balanced it out. Certainly wasn't me.
scrot
Heh, it didn't occur to me that he needed to load it dynamically. Woops. :)
Lunchy
+6  A: 

Use Assembly.GetTypes() to get a collection of all the types, or Assembly.GetType(name) to get a particular type.

You can then create an instance of the type with a parameterless constructor using Activator.CreateInstance(type) or get the constructors using Type.GetConstructors and invoke them to create instances.

Likewise you can get methods with Type.GetMethods() etc.

Basically, once you've got a type there are loads of things you can do - look at the member list for more information. If you get stuck trying to perform a particular task (generics can be tricky) just ask a specific question an I'm sure we'll be able to help.

Jon Skeet
+1  A: 

If you want to dynamically load an assembly, and then invoke methods from classes therein, you need to perform some form of dynamic invoke.

Check here for basic advice on that.

The only bit missing is how to get the type itself, which can easily be retrieved wth code like this:

foreach (Type t in assemblyToScan.GetTypes())
        {
            if(condition)
                //do stuff
        }

And if you simply want to use the assembly statically (by having the assembly available at compile time), then the answer fom Launcy here on this page is the way to go.

kek444
+1  A: 

This is how you can get the classes if you know the type.

Assembly assembly = Assembly.LoadFrom("C:\\dll\\test.dll");

// Load the object
string fullTypeName = "MyNamespace.YourType";

YourType myType = assembly.CreateInstance(fullTypeName);

The full type name is important. Since you aren't adding the .dll you can't do a Using because it is not in your project.

If you want all I would just Jon Skeet answer.

David Basarab