Sometimes in code you want to include a link to the users MySite url in a string. This is helpful when doing things like writing out sets of user names in a WebPart, and want to include a link to more information regarding the user. You can accomplish this pretty easy by tapping into the SharePoint Object Model, and is a nice enhancement that adds a little bit of elegancy to a WebPart.
The first thing that you have to do is build a small test in order to determine whether the user has been authenticated to SharePoint. This can be done using the IsAuthenticated property against the user identity within the current site context, nothing real fancy here. This will be passed into the _curUser global variable (a private string) in the WebPart class.
SPWeb web = SPControl.GetContextWeb(this.Context);
this._curUser = web.CurrentUser.LoginName;
Afterwords, you can loop through all the site collection using the sites property of the SPWebApplication class with a foreach loop. Following, using the SPWeb.WebTemplate property will get the name of the site definition that was used to create a relevant site. Since the SharePoint site definitions are explicitly named within the SharePoint 12 hive, you can test for the folder name of the MySite site definition by checking whether the return is equivalent to the string “SPSPERS” (the name of the MySite site definition). The if statement is extended in order to pass the current users login information to properly match it to the right user. Following, you can return the url of the user MySite by using the SPWeb.Url property.
foreach (SPSite site in webapp.Sites)
if (site.RootWeb.WebTemplate.ToUpper().StartsWith(“SPSPERS”) && site.Owner.LoginName.Equals(this._curUser))
That’s all! Now you have a reference to the current user’s my site. You can decorate this within your rendered WebPart HTML stream by doing a similiar site definition test to do things like parse out an image to make your Webpart property by doing (web.WebTemplate.ToUpper().StartsWith(“SPSPERS”)).