如何获取登录远程计算机的用户的登录ID?

时间:2015-02-10 13:27:30

标签: c# windows tasklist

我使用以下代码通过远程桌面获取当前登录用户

  public string connect(string machineName)
        {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.FileName = "cmd.exe";
                string command = "/C tasklist /v /fo list /fi \"imagename eq explorer.exe\" /s " + machineName;
                startInfo.Arguments = command;
                process.StartInfo = startInfo;
                startInfo.RedirectStandardOutput = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.Start();
                string strOutput = process.StandardOutput.ReadToEnd();
                if(strOutput.Contains("\\"))
                {
                int qindex = strOutput.IndexOf("\\");
                int rindex = strOutput.IndexOf("\r", qindex);
                string substring = strOutput.Substring((qindex + 1), (rindex - qindex));
                return substring;
                }
        }

但是这个过程需要非常长的时间(超过1分钟)来获取远程用户名。我无法运行wmic,因为远程计算机中未启用RPC。

我也试过以下

    string UNC = "\\\\";
    UNC += machineName;
    UNC += "\\C$\\Users";
    DirectoryInfo di = new DirectoryInfo(UNC);
    DirectoryInfo[] dirs = di.GetDirectories("*", SearchOption.TopDirectoryOnly);
    var Myfile = dirs.OrderByDescending(f => f.LastWriteTime).First();

但这并不总是可靠的,因为即使用户已登录,用户名目录也不会更新。

是否有更简单的过程来获取远程用户名

0 个答案:

没有答案