Differentiating File/Folder in SharePoint Eventreceiver

EventReceiver

You can hook SharePoint eventreceivers to lists and libraries to execute custom code whenever a new document is being uploaded to a document library. The ‘ItemAdding’ event fires when a user adds a new document to a library, but also whenever a new folder is created. However, due to the vast variety of ways to upload a document (one document, multi-document, WebDAV, Office, WebService, etc.), the event always seems to behave a little different.

Having a reliable way to check whether the user added a new document or created a new folder in a document library is key for a solid eventreceiver.

I have written a neat little extension method which will return the FileSystemObjectType of the new item:

public static class SPItemEventPropertiesExtensions
{
    public static SPFileSystemObjectType FSOType(this SPItemEventProperties properties)
    {
        object filesizeObj = properties.AfterProperties["vti_filesize"];
        if (filesizeObj != null)
        {
            int filesize = 0;
            if (Int32.TryParse(filesizeObj.ToString(), out filesize))
            {
                return (filesize > 0) ? SPFileSystemObjectType.File : SPFileSystemObjectType.Folder;
            }
        }
        return SPFileSystemObjectType.Folder;
    }
}

This extension method can be used in the ItemAdding event:

public override void ItemAdding(SPItemEventProperties properties)
{
	base.ItemAdding(properties);
	if (properties.FSOType() == SPFileSystemObjectType.Folder)
		return;

}

About the author

Alain

You can leave a response, or trackback from your own site.

One Response to “Differentiating File/Folder in SharePoint Eventreceiver”

  1. Martin says:

    Or you can use this code:
    string fileSystemObjectType = (string)properties.AfterProperties[“FileSystemObjectType”];
    bool isFolder = fileSystemObjectType != null && fileSystemObjectType == “Folder”;

Leave a Reply to Martin