Wednesday, June 2, 2010

SharePoint 2007 Web Service: Create Folder in Document Library

Use lists.asmx to create folder in a document library through a desktop application

Below is the C# function to call the lists.asmx MOSS Web Service to create folders in a document library.
Add reference to lists.asmx to your project and use the following code:



private void CreateFolder(string strPath, string strListName)
{

try
{
#region Connect to URL

this.m_objWSSListService.Url = this.cmbURL.Text.Trim('/') + "/_vti_bin/lists.asmx";

string sDomain = string.Empty;
string sUserName = this.txtLogin.Text.Trim();
if (sUserName.IndexOf("\\") > 0)
{
    sDomain = sUserName.Split("\\".ToCharArray())[0];
    sUserName = sUserName.Split("\\".ToCharArray())[1];
}

this.m_objWSSListService.Credentials = new System.Net.NetworkCredential(sUserName, this.txtPassword.Text.Trim(), sDomain);

#endregion

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.XmlElement Batch = xmlDoc.CreateElement("Batch");

Batch.SetAttribute("OnError", "Continue");
Batch.SetAttribute("ListVersion", "0");
string strBatch = "<method id="1" cmd="New">";
strBatch = strBatch + "<field name="ID">New</field>";
strBatch = strBatch + "<field name="FSObjType">1</field>";
strBatch = strBatch + "<field name="FileRef">" + strPath + "</field></method>";

Batch.InnerXml = strBatch;
XmlNode ndReturn = this.m_objWSSListService.UpdateListItems(strListName, Batch);
if (ndReturn.FirstChild.FirstChild.InnerText != "0x00000000")
{
    this.WriteLog(ndReturn.InnerText);
}

this.WriteLog("Create Operation - List:" + strListName + " - Folder: " + strPath);


}
catch (System.Exception ex)
{
this.WriteLog(ex.ToString());
}

}

2 comments:

  1. Hi Mate,

    In your sample code can you please let me know what would the values for variables look like?

    string strPath
    string strListName

    In my case the Sharepoint base URL is :-

    http://DevSPServer:6165/sites/dmDev/_vti_bin/Lists.asmx
    Base folder is "Projects"
    And would like to create folder "sub1" within "Projects" folder

    Thanks
    Nits

    ReplyDelete
  2. strListName = Library1

    strPath = http://DevSPServer:6165/sites/dmDev/Library1/Projects/Sub1

    ReplyDelete

Official SharePoint Documentation

I have recently contributed to the official SharePoint documentation for developement. Check it out here: https://docs.microsoft.com/en-us...