2008-10-30 78 views
26

我正在尋找一種簡單的方法來獲取當前Windows用戶帳戶的SID。我知道我可以通過WMI來實現,但我不想走這條路。如何獲取當前Windows帳戶的SID?

向所有在C#中回答未指定C++的人道歉。 :-)

+0

編程語言/環境? – 2008-10-30 18:31:57

回答

43

在Win32,呼叫GetTokenInformation,傳遞一個令牌手柄和TokenUser恆定。它將爲您填寫TOKEN_USER結構。那裏的一個元素是用戶的SID。這是一個BLOB(二進制),但可以使用ConvertSidToStringSid將它變成一個字符串。

要獲取當前令牌句柄,請使用OpenThreadTokenOpenProcessToken

如果你更喜歡ATL,它有CAccessToken類,它有各種有趣的東西。

.NET有Thread.CurrentPrinciple屬性,它返回一個IPrincipal引用。你可以得到SID:

IPrincipal principal = Thread.CurrentPrincipal; 
WindowsIdentity identity = principal.Identity as WindowsIdentity; 
if (identity != null) 
    Console.WriteLine(identity.User); 

此外,在.NET中,可以使用WindowsIdentity.GetCurrent(),它返回當前用戶ID:

WindowsIdentity identity = WindowsIdentity.GetCurrent(); 
if (identity != null) 
    Console.WriteLine(identity.User); 
2

​​3210有幾個不同的方法,你可以試試... ...你沒有提到你想要的語言在溶液中。

如果你想通過一個批處理文件或東西來訪問它,你可以看作爲PsigetSid Sysinternals。它將SID轉換爲名稱,反之亦然。

0

你沒有指定你想要的語言。但是,如果您希望使用C#,本文將提供WMI方法以及使用Win32 API的更快(更詳細)的方法。

http://www.codeproject.com/KB/cs/processownersid.aspx

我不認爲有目前這樣不使用WMI或在Win32 API的另一種方式。

6

這應該給你你需要的東西:

using System.Security.Principal;

...

變種SID = WindowsIdentity.GetCurrent()用戶。

的WindowsIdentity的用戶屬性返回SID,每MSDN Docs

2

在C#中,你可以使用

using Microsoft.Win32.Security;

...

string username = Environment.UserName + "@" + Environment.GetEnvironmentVariable("USERDNSDOMAIN");

Sid sidUser = new Sid (username);

或...

using System.Security.AccessControl;

using System.Security.Principal;

...

WindowsIdentity m_Self = WindowsIdentity.GetCurrent();

SecurityIdentifier m_SID = m_Self.Owner;");

1

我發現了另一種方式來獲得SID:

System.Security.Principal.WindowsIdentity id = System.Security.Principal.WindowsIdentity.GetCurrent(); 
string sid = id.User.AccountDomainSid.ToString(); 
0

這是我認爲最短的一個。

UserPrincipal.Current.Sid; 

可用.NET> = 3.5

5
ATL::CAccessToken accessToken; 
ATL::CSid currentUserSid; 
if (accessToken.GetProcessToken(TOKEN_READ | TOKEN_QUERY) && 
    accessToken.GetUser(&currentUserSid)) 
    return currentUserSid.Sid(); 
+0

這非常簡潔。 – 2016-10-13 19:50:59

0

而且在本機代碼:

function GetCurrentUserSid: string; 

    hAccessToken: THandle; 
    userToken: PTokenUser; 
    dwInfoBufferSize: DWORD; 
    dw: DWORD; 

    if not OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, ref hAccessToken) then 
     dw <- GetLastError; 
     if dw <> ERROR_NO_TOKEN then 
      RaiseLastOSError(dw); 

     if not OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, ref hAccessToken) then 
      RaiseLastOSError; 
    try 
     userToken <- GetMemory(1024); 
     try 
      if not GetTokenInformation(hAccessToken, TokenUser, userToken, 1024, ref dwInfoBufferSize) then 
       RaiseLastOSError; 
      Result <- SidToString(userToken.User.Sid); 
     finally 
      FreeMemory(userToken); 
    finally 
     CloseHandle(hAccessToken);