获取已登录用户的AppData \ Local文件夹

我目前正在使用:

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) 

检索当前用户的AppData\Local路径。 该程序需要提升权限,并在标准用户会话下运行它会抛出需要管理员登录凭据的提示。 以管理员(不同用户)身份登录显然会更改程序的活动用户。 返回的文件夹路径因此是管理员而不是标准用户使用的路径。

预期结果:

 C:\Users\StandardUser\AppData\Local 

实际结果:

 C:\Users\Administrator\AppData\Local 

有没有办法获得特定用户的AppData \ Local路径? 与获取任意用户的路径相比,获取已记录的用户名或凭据不是问题。 该应用程序基于WPF,其所需权限由manifestEcecutionLevel requestedEcecutionLevel (requireAdministrator)在清单文件中设置。

要获取其他用户的信息,您需要知道该用户的用户名/密码, 如此问题中所述 。

所以我想提出另一种解决方案:

1.-而不是使用requestedExecutionLevel作为应用程序,删除它并以记录的用户身份运行它。 这样您就可以轻松访问特殊文件夹路径并可以记录它。

2.-以管理员身份重启您的应用程序

示例代码(在App.xaml.cs中):

 private void Application_Startup(object sender, StartupEventArgs e) { if (!IsRunAsAdmin()) { // here you should log the special folder path MessageBox.Show(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); // Launch itself as administrator ProcessStartInfo proc = new ProcessStartInfo(); proc.UseShellExecute = true; proc.WorkingDirectory = Environment.CurrentDirectory; proc.FileName = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); proc.Verb = "runas"; try { Process.Start(proc); } catch { // The user refused the elevation. // Do nothing and return directly ... return; } System.Windows.Application.Current.Shutdown(); // Quit itself } else { MessageBox.Show("The process is running as administrator", "UAC"); } } internal bool IsRunAsAdmin() { WindowsIdentity id = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(id); return principal.IsInRole(WindowsBuiltInRole.Administrator); } 

此示例代码用于WPF应用程序,但可以在winforms应用程序中完成相同的操作。

参考: UAC自我提升