我想通过 ID 获取目录/文件夹的位置。
例如,Downloads 文件夹有 ID knownfolder:{374DE290-123F-4565-9164-39C4925E467B}
,当我将其输入到 windows 资源管理器的地址栏中时,它会将我重定向到 downloads 文件夹。
这里有一个这些 ID 和相应文件夹的列表,所以我可以硬编码这些 ID 并像这样查找它们,但我不想这样做,除非它是唯一的方法。
还有另一种方法可以正确地得到我想要的吗?
我想通过 ID 获取目录/文件夹的位置。
例如,Downloads 文件夹有 ID knownfolder:{374DE290-123F-4565-9164-39C4925E467B}
,当我将其输入到 windows 资源管理器的地址栏中时,它会将我重定向到 downloads 文件夹。
这里有一个这些 ID 和相应文件夹的列表,所以我可以硬编码这些 ID 并像这样查找它们,但我不想这样做,除非它是唯一的方法。
还有另一种方法可以正确地得到我想要的吗?
从这里偷来的。进一步看,唯一的方法是使用 WinAPI/PInvoke
public static class KnownFolderFinder
{
private static readonly Guid CommonDocumentsGuid = new Guid("ED4824AF-DCE4-45A8-81E2-FC7965083634");
[Flags]
public enum KnownFolderFlag : uint
{
None = 0x0,
CREATE = 0x8000,
DONT_VERFIY = 0x4000,
DONT_UNEXPAND= 0x2000,
NO_ALIAS = 0x1000,
INIT = 0x800,
DEFAULT_PATH = 0x400,
NOT_PARENT_RELATIVE = 0x200,
SIMPLE_IDLIST = 0x100,
ALIAS_ONLY = 0x80000000
}
[DllImport("shell32.dll")]
static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);
public static string GetFolderFromKnownFolderGUID(Guid guid)
{
return pinvokePath(guid, KnownFolderFlag.DEFAULT_PATH);
}
public static void EnumerateKnownFolders()
{
KnownFolderFlag[] flags = new KnownFolderFlag[] {
KnownFolderFlag.None,
KnownFolderFlag.ALIAS_ONLY | KnownFolderFlag.DONT_VERFIY,
KnownFolderFlag.DEFAULT_PATH | KnownFolderFlag.NOT_PARENT_RELATIVE,
};
foreach (var flag in flags)
{
Console.WriteLine(string.Format("{0}; P/Invoke==>{1}", flag, pinvokePath(CommonDocumentsGuid, flag)));
}
Console.ReadLine();
}
private static string pinvokePath(Guid guid, KnownFolderFlag flags)
{
IntPtr pPath;
SHGetKnownFolderPath(guid, (uint)flags, IntPtr.Zero, out pPath); // public documents
string path = System.Runtime.InteropServices.Marshal.PtrToStringUni(pPath);
System.Runtime.InteropServices.Marshal.FreeCoTaskMem(pPath);
return path;
}
}
然后你可以这样调用:
var folder = KnownFolderFinder.GetFolderFromKnownFolderGUID(new Guid("374DE290-123F-4565-9164-39C4925E467B");
我认为您正在寻找 Environment.SpecialFolder (系统命名空间):
https://msdn.microsoft.com/en-us/library/system.environment.specialfolder(v=vs.110).aspx
// Sample for the Environment.GetFolderPath method
using System;
class Sample
{
public static void Main()
{
Console.WriteLine();
Console.WriteLine("GetFolderPath: {0}",
Environment.GetFolderPath(Environment.SpecialFolder.System));
}
}
/*
This example produces the following results:
GetFolderPath: C:\WINNT\System32
*/