如何获取默认用户文件夹(例如c:\ users \ Default)

时间:2013-06-14 11:24:19

标签: c# .net

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

有人可以通过编程方式告诉我如何获取默认用户文件夹(甚至更好的默认用户AppData本地文件夹路径,例如c:\ users \ Default \ AppData \ Local),因为我需要将一些文件复制到此文件夹中?

谢谢

3 个答案:

答案 0 :(得分:6)

网上有很多文章描述了如何更改默认用户个人资料路径:

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

e.g。 %系统驱动%\用户\默认

我找到了这个页面来获取系统驱动器: How to get current windows directory e.g. 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();
}

答案 1 :(得分:3)

来自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 {{1}},而不是默认用户。

答案 2 :(得分:1)

您不能因为拒绝访问该文件夹,因此该文件夹仅供Microsoft使用。我确定环境或任何其他类不会为您提供此类功能。这只能用某种黑客攻击吗?

相关问题