Prevent Duplicate Documents in SharePoint Document Library Programatically

Let's assume the business scenario here where you need to prevent the Business users from uploading the same document into a SharePoint doucment libary twice.
 
This can't be achieved through any of the OOTB Features.  There is a way to implement this and this is via using SharePoint Event Recevier in Server Side object model.
 
Here is the Code Snippet presented below to achieve the given scenario.
 
  1. public override void ItemAdding(SPItemEventProperties properties)  
  2.         {  
  3.             base.ItemAdding(properties);  
  4.             if (CheckforDuplicates())   
  5.             {  
  6.                 try  
  7.                 {  
  8.             properties.Cancel = true;  
  9.                     properties.ErrorMessage = "Please choose different document to upload The one you are trying to upload is already there!!.";  
  10.                 }  
  11.                 catch (InvalidCreatorIdException ex)  
  12.                 {  
  13.                     properties.Cancel = true;  
  14.                     properties.ErrorMessage = "Duplicate Document Name";  
  15.                     properties.InvalidateListItem();  
  16.                     
  17.                 }  
  18.             }  
 Happy SharePointing :-)
 
Feel Free to Comment for any suggestions or improvements. 
Ebook Download
View all
Learn
View all