tags:

views:

1788

answers:

4

In an aspx page I get the Windows username with the function Request.LogonUserIdentity.Name. This function returns a string in the format "domain\user". Is there some function to only get the username, without resorting to the IndexOf and Substring, like this?

public static string StripDomain(string username)
{
    int pos = username.IndexOf('\\');
    return pos != -1 ? username.Substring(pos + 1) : username;
}
+3  A: 

I don't believe so. I have got the username using these methods before-

System.Security.Principal.IPrincipal user;

user = System.Web.HttpContext.Current.User;

System.Security.Principal.IIdentity identity;

    identity = user.Identity;

return identity.Name.Substring(identity.Name.IndexOf(@"\") + 1);

or

Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(@"\") + 1);
Russ Cam
A: 

I was suggesting to use regexpes but they would be overkill. System.String.Split do the job.

string[] parts= username.Split( new char[] {'\\'} );
return parts[1];
Johan Buret
+1  A: 

If you are using .NET 3.5 you could always create an extension method to the WindowsIdentity class that does this work for you.

public static string NameWithoutDomain( this WindowsIdentity identity )
{
    string[] parts = identity.Name.Split(new char[] { '\\' });

    //highly recommend checking parts array for validity here 
    //prior to dereferencing

    return parts[1];
}

that way all you have to do anywhere in your code is reference:

Request.LogonUserIdentity.NameWithoutDomain();

Mr. Kraus
+1  A: 
static class IdentityHelpers
{
    public static string ShortName(this WindowsIdentity Identity)
    {
        if (null != Identity)
        {
            return Identity.Name.Split(new char[] {'\\'})[1];
        }
        return string.Empty;
    }
}

If you include this code, you could then just do something like:

WindowsIdentity a = WindowsIdentity.GetCurrent();
Console.WriteLine(a.ShortName);

Obviously in a web environment, you wouldn't write to the console - just an example...

BenAlabaster