private struct TOKEN_USER
{
internal SID_AND_ATTRIBUTES User; //Compiler warning comes from here.
}
[StructLayout(LayoutKind.Sequential)]
private struct SID_AND_ATTRIBUTES
{
internal IntPtr Sid;
private int Attributes;
}
Initializing the structure to default:
TOKEN_USER tokenUser = default(TOKEN_USER);
Then making the two required calls to retrieve the pointer to the structure: (not relevant to the question) using this:
GetTokenInformation(tokenhandle, TokenInformationClass.TokenUser, sid, sidlength, ref sidlength);
and then marshalling back to a structure.
tokenUser = (TOKEN_USER)Marshal.PtrToStructure(sid, tokenUser.GetType());
which works, but the compiler warns me that the 'User' field in TOKEN_USER is unassigned.
R# suggests me initializing it from the constructor:
public TOKEN_USER(SID_AND_ATTRIBUTES user) : this(user)
{
}
However, this doesn't compile, with error "Constructor cannot call itself". My question is, should i just assign it to SID_AND_ATTRIBUTES (default) to meet the compiler's requirement, or ignore it?
Test program:
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(
int dwDesiredAccess,
[MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
int dwProcessId);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(
IntPtr processHandle,
int desiredAccess,
ref IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool GetTokenInformation(
IntPtr tokenHandle,
TokenInformationClass tokenInformationClass,
IntPtr tokenInformation,
int TokenInformationLength,
ref int ReturnLength);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool IsValidSid(
IntPtr SID);
private enum TokenInformationClass
{
TokenUser = 1,
}
private const int QueryInformation = 0x400;
private const int TokenRead = 0x20008;
private struct TOKEN_USER
{
internal SID_AND_ATTRIBUTES User; //Compiler warning comes from here.
}
[StructLayout(LayoutKind.Sequential)]
private struct SID_AND_ATTRIBUTES
{
internal IntPtr Sid;
private int Attributes;
}
internal static IntPtr GetProcessHandle()
{
foreach (Process p in Process.GetProcesses())
{
using (p)
{
if (p.ProcessName == "explorer")
{
return OpenProcess(QueryInformation, false, p.Id);
}
}
}
return IntPtr.Zero;
}
public void Test()
{
IntPtr pHandle = GetProcessHandle();
IntPtr tokenHandle = IntPtr.Zero;
OpenProcessToken(pHandle, TokenRead, ref tokenHandle);
int sidlength = 0;
GetTokenInformation(tokenHandle, TokenInformationClass.TokenUser, IntPtr.Zero,
0, ref sidlength);
TOKEN_USER tokenUser = default(TOKEN_USER);
IntPtr sid = Marshal.AllocHGlobal(sidlength);
GetTokenInformation(tokenHandle, TokenInformationClass.TokenUser,sid,
sidlength, ref sidlength);
tokenUser = (TOKEN_USER)Marshal.PtrToStructure(sid, tokenUser.GetType());
if (IsValidSid(tokenUser.User.Sid))
{
Debug.WriteLine("Valid!");
}
}