Simon said:
I have created a service which uses the FileSystemWatcher to monitor
folders for file changes. I have a app.config file which specifies which
folders to watch and what to do when a change occurs.
What I would like to do is specify a class and a method which can be
invoked when that file change occurs. I can specify the name of the
class/method in the config file but the app will see it as a string.
Therefore my question is, can I invoke a class and method from a string
value. If so how would I do that.
Sure

For complete control, you'll need the assembly name and the type name of the
class and the method to call. Your code which will call the class has to be
aware at compile time of the type of the class (so implement an interface) or
if that's not the case you need to use reflection to grab the methodinfo
object to invoke the method, which is slower.
Here's an example of a routine which creates an instance of an object in a
particular assembly:
public static IDBDriver CreateDBDriverInstance(string assemblyFilename,
string namespaceToUse, string className)
{
// load the assembly
Assembly databaseDriver = Assembly.LoadFrom(assemblyFilename);
string completeClassPath = className;
if(namespaceToUse.Length > 0)
{
// there is a namespace specified, add it
completeClassPath = namespaceToUse + "." + className;
}
// create the instance
IDBDriver toReturn =
(IDBDriver)databaseDriver.CreateInstance(completeClassPath);
// return the instance
return toReturn;
}
The instance can then be invoked by calling the method directly or if you
want to invoke a method you define in the config, you'll need reflection:
IDBDriver driver =
Utils.CreateDBDriverInstance("SD.LLBLGen.Pro.DBDrivers.SqlServer.dll",
"SD.LLBLGen.Pro.DBDrivers.SqlServer", "SqlServerDBDriver");
I can now call the method if I know what to call:
driver.SomeMethod();
if I don't know what to call at compile time, because it is read from the
config file, follow this:
// get method info of method without any parameters. methodToCall is a string
// with the method name read from the config file.
MethodInfo myMethod = driver.GetType().GetMethod(mthodToCall);
// call it
myMethod.Invoke(driver, null);
Frans.