Is there a faster way to retrieve System.Environment.UserName?
System.Environment.UserName internally calls
[DllImport("advapi32.dll", CharSet=CharSet.Auto)] internal static extern bool GetUserName(StringBuilder lpBuffer, ref int nSize);
Each call seems to hit AD, thus network latency and AD query effect spe开发者_开发百科ed of execution.
Would you know if there is a better way to retrieve this value?
Something like a cached SID somewhere on the Thread maybe? So I could read UserName & SID and cache these locally (for the time of execution) and only query System.Environment.UserName when I will get new SID (or something along these lines).
Thanks,
Retrieves the user's WindowsIdentity. Name property retrieves the Domain\Name and User.Value the SID.
System.Security.Principal.WindowsIdentity.GetCurrent()
I don't know if this fits to your needs, but maybe:
System.Environment.GetEnvironmentVariable("username");
Code bellow seems to do the trick.
First get current principal on thread if not set already. each next time just use it, adds small overhead to the thread itself, but doesn't call AD each time.
Any thoughts?
if (!System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated )
System.Threading.Thread.CurrentPrincipal =
new System.Security.Principal.WindowsPrincipal(
System.Security.Principal.WindowsIdentity.GetCurrent());
userName = System.Threading.Thread.CurrentPrincipal.Identity.Name;
精彩评论