This is some example code that demonstrates checking if a folder exists in a SharePoint list.

private void CreateFolderInList(string folderName, string listName, SPListCollection listCollection)
{
    try
        {
            //Creating folder in "Sites" Lists
            SPList list = listCollection[listName];
 
            //Check if the Folder is already available in the list
            SPQuery query = new SPQuery();
            query.Query = "<Where><And><Eq><FieldRef Name='Title'/><Value Type='Text'>" + folderName + "</Value></Eq><Eq><FieldRef Name=’FSObjType’/><Value Type=’Lookup’>1</Value></Eq></And></Where>";
            query.ViewAttributes = "Scope=\"RecursiveAll\""
 
            //Retrieve the items based on Query
            SPListItemCollection items = list.GetItems(query);
 
            //Item count is "0" if the folder does not exist
            if (items.Count == 0)
            {
                SPListItem folderItem = list.AddItem(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder);
                folderItem["Title"] = folderName;
                folderItem.Update();
                //return folderItem.Url;
            }
    }
    catch (Exception ex)
    {
    }
}


Other languages

This article is also available in the following languages: