Make you custom TFS tools clever by automatically figuring out the Project Collection

As you might have noticed, most TFS Command Line tools will automatically figure out the TFS server to connect to by somehow figuring out the TFS Server from the current folder you have open. When you're anywhere in a mapped workspace, most tools will automatically connect to that TFS Server, Project Collection and Project.

Here's how to do that yourself:


using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
var workspace = Workstation.Current.GetLocalWorkspaceInfo(Directory.GetCurrentDirectory());
if (workspace != null)
{
  teamProjectUri = workspace.ServerUri;
  var server = TfsConfigurationServerFactory.GetConfigurationServer(teamProjectUri);
  var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(teamProjectUri)
  
  var cssService = projectCollection.GetService<ICommonStructureService4>();
  var project = cssService.GetProjectByName(ProjectName)
}

This way you'll be able to create command line tools that require fewer information to function. Which just makes them easier to use :).