Saturday, June 9, 2012

Invoking a static method through reflection

For example, you have a program that requires to download the updated version from the Internet through an updater program. And this updater program is a standalone EXE program which was shared among other software projects.

In the main program, you may invoke the method provided in the updater program by calling InvokeMember.

public static bool RequiresUpdate(out Version latest_veresion)
{
 latest_veresion = null;
 string url = GetUpdateUrl();
 string info_file_name = GetInfoFile();
 
 AppDomain app_domain = AppDomain.CreateDomain("AutoUpdate.exe");
 Assembly asm = app_domain.Load(s);

 // get the class.
 Type type = asm.GetType("AutoUpdate.CAutoUpdate");

 object[] param = new object[]
      {
       url,
       info_file_name
      };

 // execute the static function
 string[] need_update = (string[])type.InvokeMember("CheckUpdateInfo", 
       BindingFlags.Default | BindingFlags.InvokeMethod, 
       null, 
       null, 
       param);

 if (need_update != null
  && need_update.Length > 0)
 {
  string[] v = need_update[0].Split('=');
  if (v.Length > 1)
  {
   latest_veresion = new Version(v[1]);
   Version current_version = Assembly.GetExecutingAssembly().GetName().Version;

   if (latest_veresion > current_version)
   {
    AppDomain.Unload(app_domain);
    return true;
   }
  }
 }

 AppDomain.Unload(app_domain);

 return false;   
}

No comments:

Post a Comment