2012-03-15 97 views
1

如何从系统中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(); 是否有任何可用的方法获取登录用户名

+0

您是否在寻找谁在登录到计算机或谁登录到您的Asp.Net网站?你也使用Asp.Net成员? – Gage 2012-03-15 12:32:34

+0

我想在窗口服务whib中获取用户名| chb – 2012-03-15 13:29:32

回答

4

你试过吗?

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; 
    } 
+0

当它在窗口服务中使用时,它返回系统而不是真实名称,使用外部窗口服务,它工作正常 – 2012-03-15 13:27:47

+1

@rizwan shahid:也许这将帮助http:// www.debugging.com/bug/20243 – Guillaume 2012-03-15 13:38:40

1

除非我没有正确理解你,我相信这只是:

using System.Security.Principal; 

this.nametext = WindowsIdentity.GetCurrent().Name; 
+1

尽管每件事情都很清楚,那么为什么你会感到困惑? – 2012-03-15 12:30:48

+2

从来没有说我很困惑。 – Anonymous 2012-03-15 12:33:23

+0

你的ans是正确的,但获取域名的用户名。 – 2012-03-15 12:37:20