开发者

Get current username from a program started as Local System Account [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 1 yea开发者_C百科r ago.

Improve this question

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:

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";
}

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


If you're not taking any measures to launch your program as a different user (CreateProcessAsUser et al.) then it's going to run as the same user as the calling program.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜