Listen/Subscribe to File Events

Product version:

EPiServer CMS 6.0 / R2

Document version:

1.0

Document last saved:

{DynamicContent:PagePropertyPlugin}

The base for File Event subscription is the UnifiedFile and UnifiedDirectory classes. They are abstraction classes of the underlying file system and the facade for EPiServer CMS and file management.

UnifiedFile triggers events (both pre- and post-events) to subscribers when:

  • a file is deleted
  • a file is checked out
  • a file is checked in
  • a file-checkout is undone
  • a file is moved
  • a file is copied
  • a file is changed

UnifiedDirectory triggers events (both pre- and post-events) to subscribers when:

  • a file is added
  • a directory is added
  • a directory is moved
  • a directory is copied
  • a directory is deleted

Since UnifiedFile and UnifiedDirectory are highly abstract classes in the EPiServer CMS object hierarchy, there is no knowledge of who (logged-in EPiServer CMS user) performed the operation. This makes more sense since underlying FileSystems (such as NativeFileSystem) can have a non-EPiServer CMS user manipulating files directly outside the admin UI. It is not recommended to use the local file directory used by EPiServer CMS directly since other functionality may rely on events being triggered, for example Workflows.

The sample code snippet below illustrates how to subscribe on File events. The example class is a singleton instance storing the list of events (as strings) triggered by UnifiedFile. In a real-life scenario, the listener for events might be implemented differently.

 

public class Subscriber
{
    private static Subscriber instance = null;
    private static IList<string> events = new List<string>();
    
    static Subscriber()
    {
        UnifiedFile.UnifiedFileMoved
            += new UnifiedFileEventHandler(UnifiedFile_FileMoved);
    }

    public static void UnifiedFile_FileMoved(UnifiedFile sender,
        UnifiedVirtualPathEventArgs args)
    {
        events.Add("File moved from: " +
        args.VirtualPath +
        " to:" +
        args.NewVirtualPath);
    }

    public static Subscriber Instance
    {
        get
        {
            if (instance == null)
                instance = new Subscriber();
            return instance;
        }
    }

    public IList<string> GetEvents()
    {
        return events;
    }
}