Adding new folder on SharePoint 2013 using C#

You can easily add a folder to your document library using the GUI but what if you are migrating from a different environment. This is when you need to write custom code to automatically create folders. First you will need to create a console project on the Visual Studio. I am using Visual Studio 2010. Then you will need to add a web reference on this project that points to your SharePoint 2013 web services. URL to SharePoint web services should be http://localhost/_vti_bin/Lists.asmx where you can replace the localhost with your server URL. Once the web reference has been added, you can use the code below to create a method on your class. You can call this method to add the new folder to your SharePoint Document Library.
public void CreateFolder(string folderLocation, string folderName){
ListsService.Lists listWebService = new ListsService.Lists(); // listWebService is the name given to the web reference
string xmlCommand;
XmlDocument doc = new XmlDocument();
xmlCommand = "<Method ID='1' Cmd='New'><Field Name='FSObjType'>1</Field><Field Name='BaseName'>" + folderLocation + folderName + "</Field><Field Name='ID'>New</Field></Method>";
XmlElement ele = doc.CreateElement("Batch");
ele.SetAttribute("OnError", "Continue");
ele.InnerXml = xmlCommand;
listWebService.Credentials = System.Net.CredentialCache.DefaultCredentials;
XmlNode node1 = listWebService.UpdateListItems("Document Library", ele); //"Document Library" should be replaced with the name for your Document Library.

Leave a Reply

Your email address will not be published. Required fields are marked *