tags:

views:

6923

answers:

5

Hi there,

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++. :-)

+1  A: 

CodeProject has a few different methods you can try... You didn't mention what languages you wanted a solution in.

If you want to access it via a batch file or something, you can look as PsGetSid by Sysinternals. It translates SIDs to names and vice versa.

Kevin Fairchild
+1  A: 

You didn't specify what language you want. But if you're up for C# this article offers both the WMI method as well as a faster (while more verbose) method utilizing the Win32 API.

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

I don't think there's currently another way of doing this without using WMI or the Win32 API.

Mel Green
+3  A: 

This should give you what you need:

using System.Security.Principal;

...

var sid = WindowsIdentity.GetCurrent().User;

The User property of WindowsIdentity returns the SID, per MSDN Docs

Jeffrey Meyer
+19  A: 

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);
Roger Lipscombe
+2  A: 

In C# you can use either

using Microsoft.Win32.Security;

...

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

Sid sidUser = new Sid (username);

Or...

using System.Security.AccessControl;

using System.Security.Principal;

...

WindowsIdentity m_Self = WindowsIdentity.GetCurrent();

SecurityIdentifier m_SID = m_Self.Owner;");

silverbugg