Sharepoint API to Convert I:0#.w|DOMAIN\USERNAME to DOMAIN\USERNAME

Since Sharepoint 2013 and after, it is very common that when we get username not with value format “Domain\Username” but with value format “i:0#.w|DOMAIN\USERNAME”

Here as below the sample function code to get user with value format “Domain\UserName” again. Yes we also can do it with split string but since we are on SharePoint development we should better use Sharepoint API on that.

All it up to us to decide 🙂

public static string GetUsernameFromClaim(string claimsEncodedUsername, SPUser spUser)
{
string claimsUsername = claimsEncodedUsername;
try
{
SPClaimProviderManager spClaimProviderManager = SPClaimProviderManager.Local;
if (spClaimProviderManager != null)
{
if (spUser != null)
{
SPClaim userClaim = spClaimProviderManager.ConvertSPUserToClaim(spUser);
return spClaimProviderManager.ConvertClaimToIdentifier(userClaim.ToEncodedString());
}
}
}
catch (Exception ex)
{
// just return the original username.
return claimsUsername;
}
// Return the original username value if it couldn’t be resolved as a claims username
return claimsUsername;
}

 

Happy Sharepoint-ing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.