UPDATE: Get Default/Welcome Page Of A SharePoint 2010 Site

PROBLEM
I needed to find the default or “welcome page” of a SharePoint site. I needed this because I need to pass in a query string parameter to it. For example, if I passed in the string “http://www.mysite.com/staff”, it would give me “Pages/index.aspx”.

After surfing the net, the threads I read on Microsoft and other sites were not helpful at all. Most lead me to complex lines of code that used different utilities that I wasn’t familiar with. (I’m not that familiar with this stuff as it is.)

SOLUTION
I finally decided to ask the question on stackoverflow. My question was How do I get the default/welcome page of a SharePoint 2010 site?.

In a few minutes, a dude answered with a link to a thread on Microsoft. It was pretty helpful although it wasn’t complete as it gave me a few errors:

  • First it gave me an unrecognizable PublishingWeb. To solve that, I had to add the Microsoft.SharePoint.Publishing reference to the web part.
  • Second it gave me a cannot convert type SPFile to string. Trying .toString() didn’t work. Turns out SPFile has a Url function which returns a string.

The finished function is:

private string GetSPSiteUrl(string u) {
	string siteurl = "";

	using (SPSite site = new SPSite(u)) {
		using (SPWeb web = site.OpenWeb()) {

			if (PublishingWeb.IsPublishingWeb(web)) {
				siteurl = PublishingWeb.GetPublishingWeb(web).DefaultPage.Url;
			}
			else {
				siteurl = web.RootFolder.WelcomePage;
			}
		}
	}

	return siteurl;
}

UPDATE
As it turns out, this code works for sites that have permissions. Since our site is anonymous access, it gives an NT prompt.

The way to fix this issue is to add RunWithElevatedPrivileges.

private string GetSPSiteUrl(string u) {
	string siteurl = "";

	// run this code with elevated privileges
	SPSecurity.RunWithElevatedPrivileges(delegate() {

		using (SPSite site = new SPSite(u)) {
			using (SPWeb web = site.OpenWeb()) {

				// get the default page
                        	if (PublishingWeb.IsPublishingWeb(web)) {
					siteurl = PublishingWeb.GetPublishingWeb(web).DefaultPage.Url;
				}
				else {
					siteurl = web.RootFolder.WelcomePage;
				}
			}
		}
	});

	return siteurl;
}