Did you know that using WindowsPrincipal.IsInRole is ~40+% slower than doing the same work yourself?  Run the code below and you’ll see …  Don’t take me wrong – I do not suggest you avoid using IsInRole call; after all a single call is so fast on most computers that it is not even measurable using a timer…  It’s just nice to know the cost of doing business J

 

public bool IsInRoleCustom(System.Security.Principal.WindowsIdentity wi, string role)

{

    bool result = false;

 

    System.Security.Principal.IdentityReference id = new System.Security.Principal.NTAccount(role).Translate(typeof(System.Security.Principal.SecurityIdentifier));

   

    foreach (System.Security.Principal.IdentityReference group in wi.Groups)

    {

        if (group.Value == id.Value)

        {

            result = true;

            break;

        }

    }

 

    return result;

}

 

public bool IsInRoleSystem(System.Security.Principal.WindowsIdentity wi, string role)

{

    return new System.Security.Principal.WindowsPrincipal(wi).IsInRole(role);

}

 

private void Form1_Load(object sender, EventArgs e)

{

    System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();

   

    string role = "Guests";

    int cnt = 20000;

 

    long t11, t12, t21, t22;

 

    t11 = DateTime.Now.Ticks;

 

    for (int i = 1; i < cnt; i++)

    {

        bool result = IsInRoleCustom(wi, role);

    }

 

    t12 = DateTime.Now.Ticks;

 

 

    t21 = DateTime.Now.Ticks;

 

    for (int i = 1; i < cnt; i++)

    {

        bool result = IsInRoleSystem(wi, role);

    }

 

    t22 = DateTime.Now.Ticks;

 

 

    System.Diagnostics.Debug.WriteLine((t12-t11).ToString());

    System.Diagnostics.Debug.WriteLine((t22-t21).ToString());

    System.Diagnostics.Debug.WriteLine(((t22 - t21)/TimeSpan.TicksPerMillisecond).ToString());

    System.Diagnostics.Debug.WriteLine(((float) (t22 - t21) / (t12 - t11)).ToString());

}