Thursday, March 12, 2009

How to get SPUser name from User Id

Sometimes we get uniques user id from sharepoint but the requirement is for name.

This can be done in one simple line:

using (SPSite site=new SPSite(siteurl))
{
using (SPWeb web=site.OpenWeb())
{
string userName= web.AllUsers.GetByID(Convert.ToInt32(userid)).Name;
}
}


Line number 5 actually gets the user name by searching all users in the 'web' scope by searching userId.

2 comments:

BeekerMD03 said...

great tip, I was using web.Users and it was throwing a "User cannot be found" error. This works, it finds the users with the web.AllUsers correctly. Thanks.

Anonymous said...

Fine advice just as what I needed.