2011-10-30 157 views

回答

1

我不認爲你可以爲部分信任的代碼。如果您的應用程序或它的一部分可以被製作成一個完全信任的服務,如the answer指定一個related question可以檢索的會話ID。

隨後給出的會話ID,你可以找到與該會話ID的過程中獲得的實際用戶(從Getting Windows Process Owner Name抽象):

[DllImport ("advapi32.dll", SetLastError = true)] 
static extern bool OpenProcessToken (IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle); 

[DllImport ("kernel32.dll", SetLastError = true)] 
[return: MarshalAs (UnmanagedType.Bool)] 
static extern bool CloseHandle (IntPtr hObject); 

static uint TOKEN_QUERY = 0x0008; 

// ... 

public static WindowsIdentity GetUserFromSession(int sessionId) 
{ 
    return Process.GetProcesses() 
     .Where(p => p.SessionId == sessionId) 
     .Select(GetUserFromProcess) 
     .FirstOrDefault(); 
} 

public static WindowsIdentity GetUserFromProcess(Process p) 
{ 
    IntPtr ph; 
    try 
    { 
     OpenProcessToken (p.Handle, TOKEN_QUERY, out ph); 
     return new WindowsIdentity(ph); 
    } 
    catch (Exception e) 
    { 
     return null; 
    } 
    finally 
    { 
     if (ph != IntPtr.Zero) CloseHandle(ph); 
    } 
}