I want to load an assembly (dll-test.dll), and run the method GetLabel:
namespace Dlltest.Test
{
public class Main
{
public string GetLabel()
{
string test = "TestString";
return test;
}
}
}
I have the following code however I cannot get to run GetLabel:
Assembly assembly = Assembly.LoadFile(@"C:\dll-test.dll");
Type type = assembly.GetType();
var obj = Activator.CreateInstance(type);
var result = type.InvokeMember("GetLabel",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
null);
MessageBox.Show(result.ToString);
It should show a message box with TestString.
Edit
I eventually made it working with:
Assembly assembly = Assembly.LoadFile(@"C:\dll-test.dll");
var type = assembly.GetTypes();
var obj = Activator.CreateInstance(type[0]);
var result = type[0].InvokeMember("GetLabel",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
null);
MessageBox.Show(result.ToString());
In line
you’re assigning type of
assemblyvariable instead of the type that you want. Tryassembly.GetType(type_name). Moreover change “GetGabel” into “GetLabel” 🙂