views:

137

answers:

3

Im 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;
    }
+1  A: 

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.

Stefan Egli
A: 

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

vipin Paliwal
A: 

Please use below code

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