从作为本地系统帐户启动的程序中获取当前用户名 [英] Get current username from a program started as Local System Account

查看:26
本文介绍了从作为本地系统帐户启动的程序中获取当前用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序是从在 Local System Account 下运行的服务启动的(真实用户已登录).该程序的任务之一是将文件存储在网络路径上,该路径应包含当前用户名,例如\\server\\storage\\%username%,但是问题是我在读取环境变量的时候得到的是系统账号的名字而不是用户账号:

My program is started from a service that runs under the Local System Account (a real user is logged in). One of the tasks of the program is store files on a network path, which should contain the current username e.g. \\server\\storage\\%username%, but the problem is that I get the name of the system account instead of the user account when I read the environment variable:

Environment.GetEnvironmentVariable("username");

在这种情况下有没有办法获得正确的用户名?

Is there a way to get the correct username in this case?

推荐答案

我的解决方案是找出哪个用户启动了资源管理器进程:

My solution was to find out which user started the explorer process:

仅在您引用 .NET System.Management时才有效:

Will only work if you reference the .NET System.Management library:

private static string GetExplorerUser()
{
    var process = Process.GetProcessesByName("explorer");
    return process.Length > 0
        ? GetUsernameByPid(process[0].Id)
        : "Unknown-User";
}

private static string GetUsernameByPid(int pid)
{
    var query = new ObjectQuery("SELECT * from Win32_Process "
        + " WHERE ProcessID = '" + pid + "'");

    var searcher = new ManagementObjectSearcher(query);
    if (searcher.Get().Count == 0)
        return "Unknown-User";

    foreach (ManagementObject obj in searcher.Get())
    {
        var owner = new String[2];
        obj.InvokeMethod("GetOwner", owner);
        return owner[0] ?? "Unknown-User";
    }

    return "Unknown-User";
}

另一种可能是解析 qwinsta 命令的输出.

Another possibility is to parse the output of the qwinsta command.

这篇关于从作为本地系统帐户启动的程序中获取当前用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆