我有一个程序,它查找以前安装的依赖项。不幸的是,它几乎可以安装在任何地方(包括程序文件或嵌套的6-7级别,在C:/上的任意文件夹中),但有几个例外.
它永远不应该在Windows或用户目录中。由于它们通常很大(而且我不需要爬行用户路径),所以我想将它们排除在扫描之外。
我知道我可以使用Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)获取当前用户配置文件的路径,但是是否有一种通用的方法来获取根用户文件夹(我的机器上的C:\Users)?
我的工作计划是获取当前用户配置文件的父文件夹,但我不确定是否会出现边缘情况,这样做不会总是给出正确的结果。
发布于 2014-05-27 21:03:48
据我所知,.NET中没有任何东西能够做到这一点。但是,如果您的目标是Vista或更新版本,则可以通过对SHGetKnownFolderPath的P/Invoke来实现
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(GetFolderOfUsers());
Console.ReadLine();
}
private static string GetFolderOfUsers()
{
if (Environment.OSVersion.Version.Major >= 6)
{
IntPtr pPath;
var code = SHGetKnownFolderPath(new Guid("0762D272-C50A-4BB0-A382-697DCD729B80"), //Guid of FOLDERID_UserProfiles, defaults to %SystemDrive%\Users
0, IntPtr.Zero, out pPath);
string s = System.Runtime.InteropServices.Marshal.PtrToStringUni(pPath);
System.Runtime.InteropServices.Marshal.FreeCoTaskMem(pPath);
return s;
}
else
{
throw new NotSupportedException("You must be using Vista or newer");
}
}
[DllImport("shell32.dll")]
static extern int SHGetKnownFolderPath(
[MarshalAs(UnmanagedType.LPStruct)] Guid rfid,
uint dwFlags,
IntPtr hToken,
out IntPtr pszPath // API uses CoTaskMemAlloc
);
}https://stackoverflow.com/questions/23898399
复制相似问题