is it possible to check for the presence of a DLL file and if it is present run some code that is accessing the DLL, but if you then remove the DLL file the code will not be run and start throwing exceptions?
Asked
Active
Viewed 667 times
1 Answers
2
You can check for the existence of the assembly (File.Exist), and if the file is found, create an instance of a type from that assembly, and call a method on it.
Something like this:
var assemblyLocation = "someLocation";
var methodToRun = "SomeMethod";
if (File.Exists(assemblyLocation))
{
var assembly = Assembly.LoadFile(assemblyLocation);
var instanceOfType = assembly.CreateInstance("SomeType");
if (instanceOfType != null) {
var methodInfo = instanceOfType.GetType().GetMethod(methodToRun);
if (methodInfo != null) {
methodInfo.Invoke(instanceOfType, null);
}
}
}
This can of course be improved if you can access the type (class or interface) of the created object, so you do not have to use reflection to execute the method.
Like this:
var assemblyLocation = "someLocation";
if (File.Exists(assemblyLocation))
{
var assembly = Assembly.LoadFile(assemblyLocation);
var instanceOfType = assembly.CreateInstance("SomeType") as SomeType;
if (instanceOfType != null) {
instanceOfType.SomeMethod();
}
}

Maarten
- 22,527
- 3
- 47
- 68