1

可以以不同于当前登录的用户身份运行 exe(使用“运行身份”)。

例如,我以“user1”身份登录到 Windows 并使用“User2”的凭据以“运行身份”启动可执行文件。

如何检索“User1”(当前登录的人)而不是“User2”(进程在其下运行)的用户名/身份?

System.Environment.UserName给User2(如预期的那样)。

4

2 回答 2

3

您可以使用WindowsIdentity.GetCurrent(). Environment.UserName或者,您可以通过属性获取登录的用户名。但是,不能保证是运行当前进程的用户。

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

请参阅http://msdn.microsoft.com/en-us/library/system.environment.username.aspx

于 2013-05-03T05:47:49.950 回答
1

我知道这是一个老问题,但也许这个解决方案对某人有用。

您可以使用“QWinsta”或“Query Session”检索当前会话用户(不是运行该应用程序的用户)。

此代码创建一个进程以使用“console”参数运行 QWinsta,当您执行此操作时,您将获得如下结果:

CMD 使用控制台参数运行 QWinsta 命令

然后您可以使用“StartInfo.RedirectStandardOutput”和“StandardOutput.ReadToEnd()”捕获该结果,将其拆分并搜索“>console”并将索引保​​存到变量中,最后您可以使用“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”或“Query Session”,您可以通过两种方式进行。

第一:复制 QWinsta.exe 从

C:\windows\system32 并将其放在您的应用程序根文件夹中(记住始终使用复制选项)

第二:提供用户名和密码来处理 StartInfo,但您需要管理员凭据并且密码必须是“system.Security.SecureString”

注意 2:并非所有版本的 Windows 都像 Windows 10 Student N 一样具有 QWinsta.exe,但您可以从其他 Windows 复制“QWinsta.exe”并使用它。

此代码已在 Win10 和 Win8 上测试过

于 2018-10-22T16:26:02.093 回答