如何获得默认用户文件夹(例如c: Users Default)

本文关键字:Users Default 例如 何获得 默认 用户 文件夹 | 更新日期: 2023-09-27 18:18:18

我看了看环境。GetFolderPath方法和System.Environment.SpecialFolder enum,但我看不到任何返回Default Users文件夹路径的内容。

有人能告诉我如何获得默认用户文件夹(甚至更好的默认用户AppData本地文件夹路径,例如c:' Users 'Default'AppData'Local)编程,因为我需要复制一些文件到这个文件夹?

谢谢

如何获得默认用户文件夹(例如c: Users Default)

网上有很多文章描述如何更改默认用户配置文件路径:

http://support.microsoft.com/kb/214636

http://www.nextofwindows.com/how-to-change-user-profile-default-location-in-windows-7/

它们都说当前默认配置文件路径存储在以下注册表位置:

HKEY_LOCAL_MACHINE'SOFTWARE'Microsoft'Windows NT'CurrentVersion'ProfileList

。% SystemDrive % ' '用户默认

我找到了这个页面来获取系统驱动器:如何获取当前windows目录,例如C:' in c#

Path.GetPathRoot(Environment.SystemDirectory)

我要用它。谢谢你的帮助。

我刚刚尝试了下面的代码,它返回c:' users ' default因此,不需要替换存储在注册表项中的%SystemDrive%文本。它会自动替换它。

using (RegistryKey profileListKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE'Microsoft'Windows NT'CurrentVersion'ProfileList"))
{
    string defaultPath = profileListKey.GetValue("Default").ToString();
}

LINQPad(语言:c#程序)输出'C:'Users'Default'Desktop':

代码片段
void Main()
{
    GetFolderPath(Environment.SpecialFolder.Desktop).Dump();
}
// Define other methods and classes here
[DllImport("shfolder.dll", CharSet=CharSet.Auto)]
internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, int hToken, int dwFlags, StringBuilder lpszPath);
public static string GetFolderPath(Environment.SpecialFolder folder)
{
    if (!Enum.IsDefined(typeof(Environment.SpecialFolder), folder))
    {
        throw new Exception("Crap");
    }
    StringBuilder lpszPath = new StringBuilder(260);
    SHGetFolderPath(IntPtr.Zero, (int) folder, -1, 0, lpszPath);
    string path = lpszPath.ToString();
    new FileIOPermission(FileIOPermissionAccess.PathDiscovery, path).Demand();
    return path;
}

编辑:我在LINQPad中导入了以下内容

System.Runtime.InteropServices
System.Globalization
System.Security.Permissions

我使用反射器来查看Environment.GetFolderPath,然后查看通过传递-1作为hToken指定的SHGetFolderPath,您将获得默认用户。

不能,因为对该文件夹的访问被拒绝,该文件夹仅由Microsoft使用。我确信Environment或任何其他类都不会为您提供这样的功能。也许这只能通过某种黑客手段来实现?