C#代码检查TFS上是否存在工作空间

我正在尝试创建一个自动化工具来从TFS获取最新代码。 我需要检查系统上是否存在任何具有相同名称的工作区。 如果存在则获取工作空间实例。 否则创建工作区和映射。

我发现Microsoft.TeamFoundation.VersionControl.ClientVersionControlServer有方法Workspace GetWorkspace(string workspaceName, string workspaceOwner); 获得现有的工作空间。 但是,如果系统上不存在工作空间,则会抛出exception。

所以请给我一个检查工作空间和映射是否存在的代码。

目前我有以下代码,我知道它的方法不正确

 try { //**Expected** an exception as sometimes the workspace may not exist or Deleted manually. workspace = versionControl.GetWorkspace(workspaceName, versionControl.AuthorizedUser); versionControl.DeleteWorkspace(workspaceName, versionControl.AuthorizedUser); workspace = null; } catch (Exception e) { DialogResult res = MessageBox.Show("There are no workspace mapped. I am creating a new workspace mapped to your local folder named DevFolder.", "Error", MessageBoxButtons.YesNo); if (res == DialogResult.No) { return; } } if (workspace == null) { var teamProjects = new List(versionControl.GetAllTeamProjects(false)); // if there are no team projects in this collection, skip it if (teamProjects.Count < 1) { MessageBox.Show("Please select a team project."); return; } // Create a temporary workspace2. workspace = versionControl.CreateWorkspace(workspaceName, versionControl.AuthorizedUser); // For this workspace, map a server folder to a local folder ReCreateWorkSpaceMappings(workspace); createdWorkspace = true; } 

如果您不想依赖捕获exception,可以调用QueryWorkspaces

  workspace = versionControl.QueryWorkspaces( workspaceName, versionControl.AuthorizedUser, Environment.MachineName).SingleOrDefault(); 

此代码将在此代码运行的计算机上查询用户的工作空间。 如果集合为空,它将在工作空间中返回null,否则它将返回列表中的单个项目。 在QueryWorkspaces返回更多项目(似乎不可能)的情况下,它仍然会抛出,但这对我来说似乎没问题。

现在您可以检查映射

  if (workspace !=null) { foreach(var folder in workspace.Folders) { if (!folder.IsCloaked && folder.LocalItem != "some expected path") { // mapping invalid, throw/log? } } }