3

I have implemented an application that authenticates users against active directory using LDAP. Since users are being authenticated from different domains, they log in by DOMAIN\UserName. After being logged in, I capture the username by using User.Identity.GetUserName() however this, of course, returns DOMAIN\UserName. What I need to do here now is to extract the UserName from the string returned. Any help will be appreciated.

Wairimu Murigi
  • 2,157
  • 2
  • 15
  • 19
  • 1
    possible duplicate of [How to get username without domain](http://stackoverflow.com/questions/330320/how-to-get-username-without-domain) – petelids Aug 28 '14 at 20:57
  • yes it is a duplicate.... Just realized that after posting the question. maybe I wasnt searching for the right thing. :-) – Wairimu Murigi Aug 28 '14 at 21:11

3 Answers3

7

What about User.Identity.GetUserName().Split('\\')[1] ?

Mathias Müller
  • 303
  • 3
  • 12
3

I think you're looking for Substring

string FullName =  User.Identity.GetUserName();
string UserName = FullName.Substring(FullName.IndexOf("\\")); 

(You might have to throw a + 1 right after FullName.IndexOf("\\"))

MikeH
  • 4,242
  • 1
  • 17
  • 32
0
public string RemoveDomain(string username)
{
    if (String.IsNullOrWhiteSpace(username))
        return username;

    return username.Split('\\').Last();
}

This will handle null and username without domain name as well.

Usage:

var username = RemoveDomain("Domain1\\Username");
username = RemoveDomain("Username");
username = RemoveDomain(null);
Tejas Patel
  • 1,289
  • 13
  • 25