开发者

Is there a faster way to retrieve System.Environment.UserName?

开发者 https://www.devze.com 2023-01-09 15:27 出处:网络
System.Environment.UserName internally calls [DllImport(\"advapi32.dll\", CharSet=CharSet.Auto)] internal static extern bool GetUserName(StringBuilder lpBuffer, ref int nSize);

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消