/// <summary> /// Populates an object that contains a known folder's properties /// as specified by a special path stated in <paramref name="path"/>. /// </summary> /// <param name="path">The path for the requested known folder; (a virtual path).</param> /// <returns>A known folder representing the specified name.</returns> public static IKnownFolderProperties GetFolderPropertiesFromPath(string path) { using (var kf = KnownFolderHelper.FromPath(path)) { if (kf != null) { return(KnownFolderHelper.GetFolderProperties(kf.Obj)); } } return(null); }
/// <summary> /// Gets a strongly-typed read-only collection of all the registered known folders. /// </summary> /// <returns></returns> public static Dictionary <Guid, IKnownFolderProperties> GetAllFolders() { // Should this method be thread-safe?? (It'll take a while // to get a list of all the known folders, create the managed wrapper // and return the read-only collection. var foldersList = new Dictionary <Guid, IKnownFolderProperties>(); var pathList = new Dictionary <string, IKnownFolderProperties>(); uint count; IntPtr folders = IntPtr.Zero; try { KnownFolderManagerClass knownFolderManager = new KnownFolderManagerClass(); if (knownFolderManager.GetFolderIds(out folders, out count) != HRESULT.S_OK) { return(foldersList); } if (count > 0 && folders != IntPtr.Zero) { // Loop through all the KnownFolderID elements for (int i = 0; i < count; i++) { // Read the current pointer IntPtr current = new IntPtr(folders.ToInt64() + (Marshal.SizeOf(typeof(Guid)) * i)); // Convert to Guid Guid knownFolderID = (Guid)Marshal.PtrToStructure(current, typeof(Guid)); try { using (var nativeKF = FromKnownFolderGuid(knownFolderID)) { var kf = KnownFolderHelper.GetFolderProperties(nativeKF.Obj); // Add to our collection if it's not null (some folders might not exist on the system // or we could have an exception that resulted in the null return from above method call if (kf != null) { foldersList.Add(kf.FolderId, kf); if (kf.IsExistsInFileSystem == true) { IKnownFolderProperties obj; if (pathList.TryGetValue(kf.Path.ToUpper(), out obj)) { pathList.Add(kf.Path.ToUpper(), kf); } } } } } catch { // Catch this in case we have an exotic non-existing, non-access case } } } } finally { if (folders != IntPtr.Zero) { Marshal.FreeCoTaskMem(folders); } } return(foldersList); }