0

How do I add a folder to current document library (well if the folder does not exists in the current document library)?

(Current being where ever the end user is) (I am going to add this code to itemAdded event handler)

Shoban
  • 22,920
  • 8
  • 63
  • 107

2 Answers2

0
curSPList.Items.Add("My Folder Name", SPFileSystemObjectType.Folder);

will create a new folder in any SharePoint list, including a document library. If you plan on implementing this in an event handler you can get the reference to the SPList from the "List" property of the SPItemEventProperties parameter.

Preston Guillot
  • 6,493
  • 3
  • 30
  • 40
  • Great. Will following give the current location of the document library? using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID)) using (SPWeb currentWeb = currentSite.OpenWeb(SPContext.Current.Web.ID)) – Ross Malai Apr 02 '10 at 23:00
  • If you're doing this from an event handler, that you have the current document library in scope is implicit. The overridden methods of your class, including ItemAdded, contain a SPItemEventProperties named properties in the parameter list. You can get a reference from it via its List property, IE: properties.List. properties.List.Items.Add("FolderName", SPFileSystemObjectType.Folder); is all the code you need. – Preston Guillot Apr 03 '10 at 03:00
0

Here is the final code that works. Creates a Folder "uHippo" in the current document library if "uHippo" does not exists.

public override void ItemAdded(SPItemEventProperties properties)
{
    base.ItemAdded(properties);


    using (SPSite currentSite = new SPSite(properties.WebUrl))
    using (SPWeb currentWeb = currentSite.OpenWeb())

    {   SPListItem oItem = properties.ListItem;             
        string doclibname = "Not a doclib";

        //Gets the name of the document library
        SPList doclibList = oItem.ParentList;

        if (null != doclibList)
        {
            doclibname = doclibList.Title;
        }


bool foundFolder = false; //Assume it isn't there by default

if (doclibList.Folders.Count > 0) //If the folder list is empty, then the folder definitely doesn't exist.
{
  foreach (SPListItem fItem in doclibList.Folders) 
  {
    if (fItem.Title.Equals("uHippo"))
    {
      foundFolder = true; //Folder does exist, break loop.
      break;
    }
  }
}
if (foundFolder == false) 
{
  SPListItem folder = doclibList.Folders.Add(doclibList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, "uHippo");      
  folder.Update(); 
}



    }
} 
Damjan Tomic
  • 390
  • 2
  • 11