Thursday, July 29, 2010

Referencing the current user in SharePoint Code

In this example I'm making the assumption that you have a web page or web part hosted in SharePoint that is calling a user control with a C# codebehind (i.e. a .ascx.cs file). The code here is called in the partial class.

There are 2 object references available to use in gathering current user information:

System.Web.HttpContext.Current.User.Identity has a type definition of the System.Security.Principal.IIdentity interface.

Microsoft.SharePoint.SPContext.Current.Web.CurrentUser has a type definition of the
Microsoft.SharePoint.SPUser class.

In my code if my Active Directory account is adegaston on the domain called MyDomain then the output of the following function would be:

"Login:MyDomain\adegaston; Display:Alex Degaston."

private string SampleCode()
{
string loginName = System.Web.HttpContext.Current.User.Identity.Name;
string displayName = Microsoft.SharePoint.SPContext.Current.Web.CurrentUser.Name;
string kFormat = "Login:{0}; Display:{1}.";
return String.Format(kFormat, loginName, displayName);
}

No comments:

Post a Comment