Which SharePoint version am I running?

Solutions which were developed for SharePoint Services V3 will most likely continue to work if you use them in a SharePoint Foundation environment.

But how do you find out which version your are dealing with? This is a question which might be important if you use V3 CSS elements which are not available under SharePoint Foundation.

The SharePoint version can be found from from the SPFarm.Local.BuildVersion property. For SharePoint V3 you’ll need permissions to access the configuration database to read the local farm. Otherwise it will be null.

So if we may not read the local farm, we’ll get the version from the SharePoint assembly version.

/// <summary>
/// find the SharePoint Version from the Microsoft.SharePoint.dll
/// </summary>
/// <returns>12 for SharePoint Services V3 | 14 for SharePoint Foundation</returns>
internal static string GetSharePointVersion()
{
   SPFarm farm = SPFarm.Local;
   if (farm != null)
   {
      Version buildVersion = farm.BuildVersion;
      return buildVersion.Major.ToString();
   }

   Assembly sharePointAssembly = typeof(WebPart).Assembly;
   var regex = new Regex(@"Microsoft.SharePoint, Version=(?<version>\d{2}).0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");
   Match match = regex.Match(sharePointAssembly.FullName);
   Group versionNumber = match.Groups["version"];
   return versionNumber.Value;
}