我目前正在使用:
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
检索当前用户的 AppData\Local
路径。该程序需要更高的权限,在标准用户 session 下运行它会抛出要求管理员登录凭据的提示。以管理员身份(不同用户)登录显然会更改程序的事件用户。因此,返回的文件夹路径是管理员的,而不是标准用户使用的。
预期结果:
C:\Users\StandardUser\AppData\Local
实际结果:
C:\Users\Administrator\AppData\Local
有没有办法获取特定用户的 AppData\Local 路径?与获取任意用户的路径相比,获取记录的用户名或凭据不是问题。该应用程序基于 WPF,其所需权限由 requestedEcecutionLevel (requireAdministrator)
在 list 文件中设置。
最佳答案
要获取其他用户的信息,您需要知道该用户的用户名/密码,如 this question 中所述。 .
所以我想抛出一个替代方案:
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 应用程序中执行相同的操作。
关于c# - 获取登录用户的 AppData\Local 文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45458728/