Search code examples
sharepointsharepoint-2010sharepoint-2007

Unique ID for list.ParentWeb.GetFolder method


I have a SharePoint custom list with folders. Each folder has items inside it. The folder names are Folder1, Folder2, Folder3 ....So on.

I want to get each folder by its unique Id in a iteration.

 SPFolder folder = list.ParentWeb.GetFolder(new Guid("{xxxxx-xxxx-xxxxxx-xxxx}"));

How can I find the unique ID for each and every folder? i.e the GUID Defined in the brackets.

Thank you...


Solution

  • I don't really get why you want to fetch the folders based on the guid, if you can fetch the guid you probably already have the folder.

    I would typically solve this using extensions. Here is a variant of what you are looking for

    using Microsoft.SharePoint;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace Herlitz.Common.Extensions
    {
        public static class SPListItemCollectionExtensions
        {
            /// <summary>
            /// Get a folder by it's guid
            /// </summary>
            /// <param name="spListItemCollection"></param>
            /// <param name="uniqueId"></param>
            /// <returns>SPFolder or Null</returns>
            public static SPFolder GetFolderByGuid(this SPListItemCollection spListItemCollection, Guid uniqueId)
            {
                var firstOrDefault = spListItemCollection.Cast<SPListItem>().FirstOrDefault(x => x.UniqueId.Equals(uniqueId));
                return firstOrDefault != null ? firstOrDefault.Folder : null;
            }
        }
    }
    

    And to query

    using (SPSite site = new SPSite(spSiteUrl))
    {
        using (SPWeb web = site.RootWeb)
        {
            SPList myList = web.GetList("thelist");
            SPFolder theFolder = myList.Folders.GetFolderByGuid(new Guid("{c4819d5f-276e-4923-81cd-a3b014f1db6g}"));
        }
    }