0

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

  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();

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

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

4

0 回答 0