Scenario: Prevent duplicate files to be uploaded to document library but allow files to be renamed in the library.

Solution:

public override void ItemUpdating(SPItemEventProperties properties)
{

    if (properties.BeforeUrl == properties.AfterUrl)
    {
        if (null != properties.ListItem && null != properties.ListItem)
        {
            if (!string.Equals(properties.ListItem["Created"], properties.ListItem["Modified"]))
            {
                properties.Cancel = true;
                properties.ErrorMessage = "File with this name already exists";
            }
        }
    }
}

If the library has no metadata then we need to add ItemAdded event handler so that we can insert a slight delay that will make sure that Created and Modified dates are different.

public override void ItemAdded(SPItemEventProperties properties)
{
    DisableEventFiring();

    // Insert a slight delay and then do item update, so that Created and Modified dates are different.
    Thread.Sleep(1000);
    properties.ListItem.Update();
    EnableEventFiring();
}

One issue that I found with this piece of code is that  if we click on edit and change any property other than Name, we will still get the error "File with this name already exists". Or for that matter if we simply click on edit and then click OK without changing any property we get the same error. This is because BeforUrl and AfterUrl are same in these two cases. I tried to use BeforeProperties and AfterProperties but unfortunately both are null in ItemUpdating event. Would like to see some workaround for it. 


0 comments

My SharePoint CodePlex Projects

SharePoint 2010 Autocomplete Lookup Field

Export Version History Of SharePoint 2010 List Items to Microsoft Excel.