从 Windows 媒体库获取目录列表

eve*_*ton 3 .net c# windows

有没有办法以编程方式查找当前在 Windows 媒体库上设置的目录列表?

例如:假设我有以下库(我为葡萄牙语道歉,但你会明白的):

在此处输入图片说明

如何以编程方式获取视频库中列出的这三个目录路径

D:\Filmes
D:\Series
D:\Videos
Run Code Online (Sandbox Code Playgroud)

这个问题几乎让我到了那里,但这不是我想要的。到目前为止,我的替代方法是尝试直接从Windows Registry 中查找。

and*_*ss6 5

终于来了!

 using System.Runtime.InteropServices;
 using System.Diagnostics;
 using System.IO;
 using System.Xml;


 [DllImport("shell32.dll")]
 private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, ref IntPtr ppszPath);

 public void GetVideoLibraryFolders()
 {
     var pathPtr = default(IntPtr);
     var videoLibGuid = new Guid("491E922F-5643-4AF4-A7EB-4E7A138D8174");
     SHGetKnownFolderPath(videoLibGuid, 0, IntPtr.Zero, ref pathPtr);

     string path = Marshal.PtrToStringUni(pathPtr);
     Marshal.FreeCoTaskMem(pathPtr);
     List<string> foldersInLibrary = new List<string>();

     using (XmlReader reader = XmlReader.Create(path))
     {
         while (reader.ReadToFollowing("simpleLocation"))
         {
             reader.ReadToFollowing("url");
             foldersInLibrary.Add(reader.ReadElementContentAsString());
         }
     }

     for (int i = 0; i < foldersInLibrary.Count; i++)
     {
         if (foldersInLibrary[i].Contains("knownfolder"))
         {
             foldersInLibrary[i] = foldersInLibrary[i].Replace("knownfolder:{", "");
             foldersInLibrary[i] = foldersInLibrary[i].Replace("}", "");

             SHGetKnownFolderPath(new Guid(foldersInLibrary[i]), 0, IntPtr.Zero, ref pathPtr);
             foldersInLibrary[i] = Marshal.PtrToStringUni(pathPtr);
             Marshal.FreeCoTaskMem(pathPtr);
         }
     }

    // foldersInLibrary now contains the path to all folders in the Videos Library

 }
Run Code Online (Sandbox Code Playgroud)

那么,我是怎么做到的呢?

首先,有此功能SHGetKnownFolderPathshell32.dll图书馆,它返回一个文件夹的路径提供的GUID(文档)。还有一个Windows 上每个已知文件夹的 GUID列表

"491E922F-5643-4AF4-A7EB-4E7A138D8174"Videos_Library文件夹的 ID 。

但是有一个问题!该函数将返回此路径:%appdata%\Microsoft\Windows\Libraries\Videos.library-ms

如果您尝试使用类似方法访问该文件夹,Directory.GetDirectories您将获得DirectoryNotFoundException. 怎么了?好吧,问题是:Videos.library-ms不是文件夹!它是一个 XML 文件。如果你用一些文本编辑器打开它,你会看到。

在发现它是一个 XML 文件后,我所要做的就是阅读它,我们将获得目录的路径。如果您打开 xml,您将看到库中的所有文件夹都在<simpleLocation>元素下。因此,您只需读取所有<simpleLocation>XML 元素,然后读取它们的子元素<url>,其中的内容包含文件夹本身的路径。

虽然这可能是结尾,但我幸运地注意到并非每个文件夹路径都被描述为文件中的常用路径.library-ms;其中一些是用 GUID 描述的(是的,我之前链接的那些),而那些knownfolder在其中具有属性。因此,在最后for,我在目录列表中搜索具有该knownfolder属性的元素。对于找到的每一个,我然后用正确的值替换它们的值,通过再次搜索 GUID 使用SHGetKnownFolderPath.

就是这样了!