2013-02-26 75 views

回答

4

讓運行該程序的用戶更容易,您可以使用Environment.UserNameSystem.Security.Principal.WindowsIdentity.GetCurrent().Name
鏈接它們之間的區別是位於下方...

現在,讓登錄的用戶的是一個小更棘手。
我使用下面的方法(我想我在這裏找到它在這裏回來)。它的作用是檢查誰是explorer.exe進程的所有者(這是登錄的用戶):

private string GetExplorerUser() 
{ 
    var query = new ObjectQuery(
     "SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'"); 

    var explorerProcesses = new ManagementObjectSearcher(query).Get(); 

    foreach (ManagementObject mo in explorerProcesses) 
    { 
     String[] ownerInfo = new string[2]; 
     mo.InvokeMethod("GetOwner", (object[])ownerInfo); 

     return String.Concat(ownerInfo[1], @"\", ownerInfo[0]); 
    } 

    return string.Empty; 
} 

上面的方法需要System.Managment DLL

更新: 上述方法工作正常,基於OP的評論 - 增加了一個選項:

獲取第一用戶名從Win32_ComputerSystem

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem"); 
ManagementObjectCollection collection = searcher.Get(); 
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"]; 
+0

非常感謝。不幸的是,我想知道這一點的原因是當不同的用戶使用/ separate開關時,啓動資源管理器,但通常不是! – fangster 2013-02-26 14:22:01

+0

謝謝,但有什麼建議嗎?我可能很愚蠢,但我盯着任務管理器,看不到合適的過程。 – fangster 2013-02-26 15:44:29

+0

增加了另一個供使用的選項。 – Blachshma 2013-02-26 19:22:29

相關問題