0

I'm returning the username from sharepoint site as a string. This is done successfully with the below code but I also get the domain with it. How can I only return the username and not the domain either through sharepoint or programmatically removing it? domain/username

 private string CurrentUserName()
    {
        string userName = "NA";
        SPContext currentContext;
        try
        {
            //Getting the current context
            currentContext = SPContext.Current;
        }
        catch (InvalidOperationException)
        {
            currentContext = null;
        }
        if (currentContext != null && currentContext.Web.CurrentUser != null)
        {
            userName = SPContext.Current.Web.CurrentUser.LoginName;
        }
        else
        {

        }
        return userName;
    }

3 Answers 3

4

Assuming the user is returned in this format

domain\username

you can do the following:

string userWithoutDomain = userName.Substring(userName.IndexOf('\\') + 1);

If the format is like this

username@domain

then the following will work

string userWithoutDomain = user.Substring(0, user.IndexOf('@'));

Probably you should test which format you have and extract the user name based on that. If the user name contains neither a @ nor a \ then you just return the entire string.

Sign up to request clarification or add additional context in comments.

Comments

0

Change name column in user information list.and u get SPContext.Current.Web.CurrentUser.Name because login name can not change.

Comments

-2

Please use below code

 site = new SPSite(SPContext.Current.Site.ID);
             web = site.OpenWeb();
            userName = web.CurrentUser.Name.ToString() ;

2 Comments

user.name is not this same as loginName my name can be "Users First" and login "oc\user01" i assume he wants "user01"
That does not answer his question at all and it is the wrong answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.