2012-03-15 70 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