Total Pageviews

Friday, 17 February 2012

How to load DLL and call its methods using C#.NET


// Unbox it to correct object
Type type = null;

String AssemblyDir = @"D:\Project\DataAccess.dll";
//AssemblyDir = AssemblyDir.TrimStart("file:\\".ToArray());

 Assembly a = Assembly.LoadFrom(AssemblyDir);
       type = a.GetType("DataAccess.DerivedClass");

   if (type != null)
       {
          BaseClass objBaseClass = (BaseClass)Activator.CreateInstance(type, args);
          resultCode = objBaseClass.MethodName(Parameters);
        }
       else
          {
              throw new Exception("Can't find correct type name or dll!"); // FATAL ERROR. Can't find correct type name or dll.
            }


Where  BaseClass is like
public class BaseClass : ICloneable
{
// this method is override by DerivedClass
 public virtual string MethodName( parameters )
 {
   throw new NotImplementedException();
 }
}
Where  DerivedClass is like
public class DerivedClass : BaseClass
{
public override sealed string MethodName(parameters)
{
// do something with parameters
}
}

No comments:

Post a Comment