Removing and adding event handlers using reflection

Recently I ran into an situation that I need to remove all the event handlers, perform some work and then re-attach all the event handlers.  This requires using reflection since we need to discover the event handler in runtime. This is useful in cases where the object itself do not have knowledge of who has attached to itself. 

The code is listed just below.  We need the FieldInfo so that we can call GetValue() to get a reference to the event delegate.  Then using EventInfo.RemoveEventHandler() and EventInfo.AddEventHandler() to detach and re-attach the handler:


// define the binding flags for reflection
var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

// Target has a event call PropertyChanged
Type type = target.GetType();
var fieldInfo = type.GetField("PropertyChanged", bindingFlags);
var eventInfo = type.GetEvent("PropertyChanged", bindingFlags);

// using GetValue() to get the reference of event delegate
var del = fieldInfo.GetValue(target) as Delegate;

// detach the event handler
if (del != null)
  eventInfo.RemoveEventHandler(target, del);

// Do you thing here!!

// re-attach the event handler
if (del != null)
  eventInfo.AddEventHandler(target, del);

Simple enough?  We can further improve this by looping through all the events and fields, so we don’t need the hardcoded event name in string.

Delete Files using C#

Example code to follow:

protected void CleanImageFolder()
{
    string imgFolder = Server.MapPath("~/lab/maskemail/img/");
    string[] imgList = Directory.GetFiles(imgFolder, "*.jpg");
    foreach (string img in imgList)
    {
        FileInfo imgInfo = new FileInfo(img);
        if (imgInfo.LastWriteTime < DateTime.Now.AddMinutes(-3))
        {
            imgInfo.Delete();
        }
    }
}
Follow

Get every new post delivered to your Inbox.