Thursday, May 5, 2011

To prevent users from creating folders in SharePoint document libraries

Using SharePoint 2007;

The OOB method to remove the "New Folder" menu will prevent users only creating folder from the standard view and users are still be able to upload/create folders from explorer view. Below is the feature code used to prevent users from creating folders in document library even in explorer view.

Feature.xml

<?xml version="1.0" encoding="utf-8"?>
<Feature  Id="62b28298-e3fc-4ccc-a2ea-3f92b7e9a21e"
          Title="Disable Folders"
          Description="Feature to disable creating new folders in document libraries in the site"
          Version="12.0.0.0"
          Hidden="FALSE"
          Scope="Web"
    ActivateOnDefault="FALSE"
          DefaultResourceFile="core"
          xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="elements.xml"/>
  </ElementManifests>
</Feature>


Elements.xml

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
 <Receivers ListTemplateId="101">
  <Receiver>
   <Name>AddingEventHandler</Name>
   <Type>ItemAdding</Type>
   <SequenceNumber>10000</SequenceNumber>
   <Assembly>AAAA.BBB.AllUsers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5</Assembly>
   <Class>AAAA.BBB.AllUsers.DisableFoldersInLib</Class>
   <Data></Data>
   <Filter></Filter>
  </Receiver>
 </Receivers>
</Elements>

Code:
 public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            //If the new created file type is "folder" then the following conditions will be true
            if ((properties.BeforeUrl != properties.AfterUrl &&
                properties.ListItem == null &&
                properties.ListItemId == 0) ||
                properties.AfterProperties["ContentType"].ToString() == "Folder")
            {
                properties.Cancel = true;
                properties.ErrorMessage = "You are not allowed to create new Folders in this document library. Please tag the files with Metadata instead of creating folders.";
            }
        }

The source code of this feature is available at Technet Gallery

4 comments:

  1. Hey,
    very thanks by sharing this script. But, how I must apply this? Could you help me?

    ReplyDelete
  2. This doesn't works for SharePoint 2010.

    ReplyDelete
  3. This doesn't seem to work for SharePoint 2010. End result: Unable to Create New folder.File System Error (65535).

    ReplyDelete
  4. For SharePoint 2010:

    if (properties.AfterProperties["vti_filesize"] == null)
    {
    //this is a folder
    }
    else
    {
    //this is a file
    }

    ReplyDelete