[英]Get logged in user's name from process running under “run as” credentials
一个人可以以不同于当前登录用户的用户身份运行exe(使用“运行方式”)。
例如,我以“ user1”身份登录Windows,并使用“ User2”的凭据以“ run as”启动可执行文件。
如何检索“ User1”(当前登录的用户)而不是“ User2”(进程在其下运行)的用户名/身份?
即System.Environment.UserName
给User2(按预期方式)。
您可以使用WindowsIdentity.GetCurrent()
获得当前线程正在其下运行的用户(不一定是登录用户)的当前身份。 或者,您可以通过Environment.UserName
属性获取登录的用户名。 但是,不能保证是用户正在运行当前进程。
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
请参阅http://msdn.microsoft.com/en-us/library/system.environment.username.aspx
我知道这是一个老问题,但也许此解决方案对某人有用。
您可以使用“ QWinsta”或“查询会话”来检索当前会话用户(而不是运行应用程序的用户)。
此代码创建一个使用“ console”参数运行QWinsta的过程,执行此操作时,您将得到如下结果:
然后,您可以使用“ StartInfo.RedirectStandardOutput”和“ StandardOutput.ReadToEnd()”捕获该结果,将其拆分并搜索“>控制台”,然后将索引保存到变量中,最后可以使用“ index + 1”获取用户在拆分数组中。
为了安全起见,我添加了“ Proc.WaitForExit(2000)”以等待最多2秒钟,然后再停止任务,否则它将永远等待,并且“ Proc.ExitCode!= 0”可以防止发生任何错误。
Process Proc = new Process();
Proc.StartInfo.UseShellExecute = false;
Proc.StartInfo.CreateNoWindow = true;
Proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Proc.StartInfo.FileName = @"qwinsta.exe";
Proc.StartInfo.Arguments = @"console";
Proc.StartInfo.RedirectStandardOutput = true;
Proc.Start();
if (!Proc.WaitForExit(2000) || Proc.ExitCode != 0)
{
try { Proc.Kill(); } catch { }
return null;
}
string Resultado = Proc.StandardOutput.ReadToEnd();
string[] Textos = Resultado.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
int Indice = 0;
foreach (string TXT in Textos) { if (TXT == ">console") { break; } else Indice++; }
return Textos[Indice + 1];
注意:如果您想使用“ QWinsta”或“查询会话”,您可以通过两种方式。
首先:从以下位置复制QWinsta.exe
C:\\ windows \\ system32并将其放在您的应用程序根文件夹中(请记住使用始终复制选项)
第二:提供用户名和密码来处理StartInfo,但是您需要管理员凭据,并且密码必须是“ system.Security.SecureString”
注意2:并非所有版本的Windows都像Windows 10 Student N一样具有QWinsta.exe,但是您可以从其他窗口复制“ QWinsta.exe”并使用它。
此代码已在Win10和Win8上经过测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.