SharePoint: Create folder hierarchy

Scenario:

We need to move a document from one document library to another document library with the condition that if folder hierarchy doesn’t exist, creates it.

Resolution:

Following code checks if folder hierarch exists or not. If exist, returns the reference of the folder, else create the hierarchy and return the reference of the newly created folder.

It takes three input. SPWeb, list name and folder path. Folder path should be like “/DocumentLibraryName/Folder1/Folder2/Folder3/Folder4”.

public SPFolder VerifyAndCreateFolder(SPWeb spWeb,string listName, string folderPath)

{

SPList spList = spWeb.Lists[listName];

string rootFolderUrl = spList.RootFolder.ServerRelativeUrl;

SPFolder spFolder = null;

if (spWeb.GetFolder(folderPath).Exists)

{

return spWeb.GetFolder(folderPath);

}

else

{

string destFolderPath = folderPath.Replace(“/” + listName + “/”,“”);

int lastIndexOfFowardSlash = destFolderPath.LastIndexOf(‘/’);

if (lastIndexOfFowardSlash < 0)

{

SPFolderCollection spFolderColl = spWeb.GetFolder(rootFolderUrl).SubFolders;

spFolder = spFolderColl.Add(destFolderPath);

return spFolder;

}

else

{

lastIndexOfFowardSlash = folderPath.LastIndexOf(‘/’);

string parentFolderURL = folderPath.Remove(lastIndexOfFowardSlash);

spFolder = VerifyAndCreateFolder(spWeb, listName, parentFolderURL);

SPFolderCollection spFolderColl = spWeb.GetFolder(rootFolderUrl).SubFolders;

spFolder = spFolderColl.Add(“/” + listName + “/” + destFolderPath);

return spFolder;

}

}

}

Advertisements

1 Comment »

  1. Anonymous said

    One line needed to be changed, but it worked for me in SP2013:
    //spFolder = spFolderColl.Add(“/” + library.Title + “/” + destFolderPath);
    spFolder = spFolderColl.Add(destFolderPath);

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: