如何获取当前Windows帐户的SID? [英] How can I get the SID of the current Windows account?
问题描述
我正在寻找一个简单的方法来获取当前Windows用户帐户的SID。我知道我可以通过WMI,但我不想走这条路线。
对于在C#中回答没有指定它的C ++的所有人都抱歉。 : - )
在Win32中,调用 GetTokenInformation ,传递令牌句柄和TokenUser常量。它将为您填写 TOKEN_USER 结构。其中的一个元素是用户的SID。这是一个BLOB(二进制),但您可以使用 ConvertSidToStringSid 将其转换为字符串。
要获取当前令牌句柄,请使用 OpenThreadToken 或 OpenProcessToken 。 p>
如果您喜欢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);
I am looking for an easy way to get the SID for the current Windows user account. I know I can do it through WMI, but I don't want to go that route.
Apologies to everybody that answered in C# for not specifying it's C++. :-)
In Win32, call GetTokenInformation, passing a token handle and the TokenUser constant. It will fill in a TOKEN_USER structure for you. One of the elements in there is the user's SID. It's a BLOB (binary), but you can turn it into a string by using ConvertSidToStringSid.
To get hold of the current token handle, use OpenThreadToken or OpenProcessToken.
If you prefer ATL, it has the CAccessToken class, which has all sorts of interesting things in it.
.NET has the Thread.CurrentPrinciple property, which returns an IPrincipal reference. You can get the SID:
IPrincipal principal = Thread.CurrentPrincipal;
WindowsIdentity identity = principal.Identity as WindowsIdentity;
if (identity != null)
Console.WriteLine(identity.User);
Also in .NET, you can use WindowsIdentity.GetCurrent(), which returns the current user ID:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity != null)
Console.WriteLine(identity.User);
这篇关于如何获取当前Windows帐户的SID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!