我正在寻找一种简单的方法来获取当前Windows用户帐户的SID.我知道我可以通过WMI做到这一点,但我不想走那条路.
向在C#中回答的所有人道歉,因为没有指定它的C++.:-)
Rog*_*mbe 50
在Win32中,调用GetTokenInformation,传递令牌句柄和TokenUser常量.它将为您填写TOKEN_USER结构.其中一个元素是用户的SID.它是BLOB(二进制),但您可以使用ConvertSidToStringSid将其转换为字符串.
要获取当前令牌句柄,请使用OpenThreadToken或OpenProcessToken.
如果你更喜欢ATL,它有CAccessToken类,里面有各种有趣的东西.
.NET具有Thread.CurrentPrinciple属性,该属性返回IPrincipal引用.你可以得到SID:
IPrincipal principal = Thread.CurrentPrincipal;
WindowsIdentity identity = principal.Identity as WindowsIdentity;
if (identity != null)
Console.WriteLine(identity.User);
Run Code Online (Sandbox Code Playgroud)
同样在.NET中,您可以使用WindowsIdentity.GetCurrent(),它返回当前用户ID:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity != null)
Console.WriteLine(identity.User);
Run Code Online (Sandbox Code Playgroud)
ATL::CAccessToken accessToken;
ATL::CSid currentUserSid;
if (accessToken.GetProcessToken(TOKEN_READ | TOKEN_QUERY) &&
accessToken.GetUser(¤tUserSid))
return currentUserSid.Sid();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35507 次 |
| 最近记录: |