473,387 Members | 1,834 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Invoke a class from a string

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.

Regards
Simon
Nov 16 '05 #1
3 4744
<"=?Utf-8?B?U2ltb24gS2luZw==?=" <Simon
Ki**@discussions.microsoft.com>> wrote:
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.


Is the method a static method? If so, just use Type.GetType with the
class name (or Assembly.GetType if it'll be in a different assembly
from the calling one) to get the type, and Type.GetMethod to get the
method itself. You can then call Invoke on the MethodInfo, passing null
as the target argument. If it's an instance method, you'll need to
create an instance of the class first, which you can do with
Activator.CreateInstance.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
Simon King wrote:
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(completeC lassPath);

// 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.DBDri vers.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.

--
Get LLBLGen Pro, productive O/R mapping for .NET: http://www.llblgen.com
My .NET Blog: http://weblogs.asp.net/fbouma
Microsoft C# MVP
Nov 16 '05 #3
Fans and Jon,

Thats exactly what I need fantastic thanks. I'll let you know how I get on.

Regards
Simon

"Frans Bouma [C# MVP]" wrote:
Simon King wrote:
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(completeC lassPath);

// 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.DBDri vers.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.

--
Get LLBLGen Pro, productive O/R mapping for .NET: http://www.llblgen.com
My .NET Blog: http://weblogs.asp.net/fbouma
Microsoft C# MVP

Nov 16 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: John Altland | last post by:
Here is my basic problem. I have a form that executes a cpu instensive algorithm occupying the first thread. When the algorithm is executed another form pops up telling the user the progress that...
16
by: Duncan Mole | last post by:
Hi, This is probably an easy one but it iy first bit of p/invoke. I am trying to use the following C struct in a call: typedef struct { BYTE SRB_Cmd; BYTE SRB_Status, BYTE ...
2
by: rawCoder | last post by:
Hi I am having this InvalidOperationException with message Cannot call Invoke or InvokeAsync on a control until the window handle has been created This is raised when i try to invoke a method...
5
by: User N | last post by:
I have a log class with static methods that grab and release a mutex as required. The log class is designed to be called from both GUI and thread pool threads, and dump output to a logfile and a...
0
by: Pawan Narula via DotNetMonster.com | last post by:
hi all, i'm using VB.NET and trying to code for contact management in a tree. all my contacts r saved in a text file and my C dll reads them one by one and sends to VB callback in a sync mode...
7
by: stephan querengaesser | last post by:
hi ng, i try to invoke a webservice-method with an filter-object, that contains value types. if i donīt want to filter the return value of the method, i have to pass a new instance of the...
9
by: Terry Olsen | last post by:
I'm running an asynchronous Socket. In the ReceiveCallback method, I need to append what is received to a textbox on the main form. I have this code: Private Sub ToChatWindow(ByVal msg As...
1
by: Steve | last post by:
I need to update my UI from a Process or worker thread. I did some readinf and basically ended up adapting an MS example to fot my needs. It all made sense until I tried it :) My process...
6
by: Dom | last post by:
I'm teaching myself about delegates and the Invoke method, and I have a few newbie questions for the gurus out there: Here are some CSharp statements: 1. public delegate void MyDelegate (int k,...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.