c# - C#获取用户登录名

标签 c# asp.net c#-4.0 c#-3.0

如何在c#中查询系统登录用户名 我用这个方法试过了

static string whoisLoggedIn(string HostOrIP)
{
     GUFlag = true;
     HostOrIP = Environment.MachineName;
     System.Management.ConnectionOptions myConnectionOptions = new System.Management.ConnectionOptions();
     myConnectionOptions.Impersonation = System.Management.ImpersonationLevel.Impersonate;

     System.Management.ManagementScope objwmiservice;
     System.Management.ManagementObjectSearcher myObjectSearcher2;
     System.Management.ManagementObjectCollection myCollection2;

     try
     {
         objwmiservice = new System.Management.ManagementScope(("\\\\" + (HostOrIP +
"\\root\\cimv2")), myConnectionOptions);
         objwmiservice.Connect();
         myObjectSearcher2 = new System.Management.ManagementObjectSearcher(objwmiservice.Path.ToString(),
"Select UserName from Win32_ComputerSystem");
         myObjectSearcher2.Options.Timeout = new TimeSpan(0, 0, 0, 0, 7000);
         myCollection2 = myObjectSearcher2.Get();
         GUFlag = false;

         foreach (System.Management.ManagementObject myObject in myCollection2)
         {
             if (!(myObject.GetPropertyValue("Username") == null))
             {
                 string Userx = myObject.GetPropertyValue("Username").ToString();
                 int posx = Userx.LastIndexOf("\\");
                 if ((posx > 0))
                 {
                     Userx = Userx.Substring((posx + 1));
                     return Userx.ToUpper();
                 }
             }
         }
         return "<Nobody>";
     }
     catch (Exception)
     {
         return "<Nobody>";
     }
     finally {

         GUFlag = false;
     }

 }

但问题是在 myObjectSearcher2.Get(); 上发生了一些时间死锁 有没有办法获取登录用户名

最佳答案

你试过吗?

Environment.UserName

它会给你当前登录windows的用户名

编辑

我在这里找到了这段代码 http://www.debugging.com/bug/20243 ,它可能会解决您的问题。

使用 WMI ( http://msdn.microsoft.com/en-us/library/system.management.aspx ) 的解决方案:

    private string GetUserName()
    {
        string result = "";
        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName, Name FROM Win32_ComputerSystem"))
        {
            foreach (ManagementObject mo in searcher.Get())
            {
                if (mo["UserName"] != null)
                    result = mo["UserName"].ToString();
                if (mo["Name"] != null)
                    result += " (" + mo["Name"].ToString() + ")";
            }
        }
        return result;
    }

关于c# - C#获取用户登录名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9719609/

相关文章:

c# - EF 6.0 多对多关系编辑

c# - 在策略模式中,处理共享行为的最佳方式是什么?

asp.net - 在内部存储之前访问过错误: Either BinaryRead,表单,文件或InputStream

asp.net - 如果 Elmah 无法访问数据库以记录异常怎么办?

c#-4.0 - 如何实例化未包含在 C# 项目中的对象?

c# - 我可以强制子类实现静态解析方法吗?

c# - 无法访问已处置的对象。交易

c# - 从 shell 运行的 ffmpeg 运行正常,但在 .NET 中调用时运行不正常

javascript - Plotly.js 图表中显示的数据错误

c# - 从 Inherited 接口(interface)调用方法时传递动态参数会抛出 RuntimeBinderException