Environment / WindowsIdentity

  • Thread starter Thread starter Peter Larsen [CPH]
  • Start date Start date
P

Peter Larsen [CPH]

Hi,

Are there any differences in the data returned from Environment.UserName and
WindowsIdentity.GetCurrent().Name (except that the domain is included in
last method) ??

BR
Peter
 
Hello All,

You can see the WindowsIdentity.GetCurrent().Name retrieves the name from
this.User
--------------------Codes--------------
this.m_name = (this.User.Translate(typeof(NTAccount)) as
NTAccount).ToString();
--------------------------------------------

If you look into this.User property implementation using Reflector, you can
find,
--------------------Codes--------------
[ComVisible(false)]
public SecurityIdentifier User
{
get
{
if (this.m_safeTokenHandle.IsInvalid)
{
return null;
}
if (this.m_user == null)
{
uint dwLength = 0;
SafeLocalAllocHandle handle =
GetTokenInformation(this.m_safeTokenHandle,
TokenInformationClass.TokenUser, out dwLength);
this.m_user = new
SecurityIdentifier(Marshal.ReadIntPtr(handle.DangerousGetHandle()), true);
handle.Dispose();
}
return this.m_user;
}
}

private static SafeLocalAllocHandle GetTokenInformation(SafeTokenHandle
tokenHandle, TokenInformationClass tokenInformationClass, out uint dwLength)
{
SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle;
dwLength = (uint) Marshal.SizeOf(typeof(uint));
bool flag = Win32Native.GetTokenInformation(tokenHandle, (uint)
tokenInformationClass, invalidHandle, 0, out dwLength);
int errorCode = Marshal.GetLastWin32Error();
int num2 = errorCode;
if (num2 == 6)
{
throw new
ArgumentException(Environment.GetResourceString("Argument_InvalidImpersonati
onToken"));
}
if ((num2 != 0x18) && (num2 != 0x7a))
{
throw new SecurityException(Win32Native.GetMessage(errorCode));
}
IntPtr sizetdwBytes = new IntPtr((long) ((ulong) dwLength));
invalidHandle = Win32Native.LocalAlloc(0, sizetdwBytes);
if ((invalidHandle == null) || invalidHandle.IsInvalid)
{
throw new OutOfMemoryException();
}
if (!Win32Native.GetTokenInformation(tokenHandle, (uint)
tokenInformationClass, invalidHandle, dwLength, out dwLength))
{
throw new
SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
}
return invalidHandle;
}

--------------------------------------------
We can see that it eventually calls into Win32Native.GetTokenInformation
API to retrieve the current user name information.
http://msdn.microsoft.com/en-us/library/aa446671(VS.85).aspx

Although from two different APIs, I think their returned value should be
same exception one include domain information.


Best regards,
Ji Zhou
Microsoft Managed Newsgroup Support Team
 
Hi Jason,

Cool work.
I just want to know if i could use either of them and from your's (and
Colbert's) explanation, both should be valid.

BR
Peter


Hi there.
 
Back
Top