首页 > 解决方案 > 如何使用 C# 代码从 TFS 签出和签入文件?

问题描述

我正在尝试创建一个窗口窗体应用程序,它可以签出、对文件进行一些编辑并签入 TFS 中的文件。

我可以使用下面的代码来完成这些操作。我面临的唯一问题是tf.exe动态获取路径。我不希望tf.exe在解决方案中硬编码路径。tf.exe我试图打开的是 Visual Studio 2017 文件夹。

foreach (string path in FilePaths)
{
  var proc = new Process
  {
    StartInfo = new ProcessStartInfo
    {
       FileName = @"C:\Program Files (x86)\Microsoft Visual Studio 
       14.0\Common7\IDE\tf.exe",
       Arguments = "checkout " + path,
       UseShellExecute = false,
       RedirectStandardOutput = true,
       CreateNoWindow = true
    }
  };
 proc.Start();
}

中提供的路径FileName应该是动态获取的。

标签: c#tfsvisual-studio-2017

解决方案


你有几个选择:

1)添加一个检查tf.exe安装位置并返回位置的功能(有点难看,当新的VS版本发布时您需要更新该功能):

private string GetTfLocation()
{
    string tfPath = "";
    // For VS 2015
    if (File.Exists(tfPath = @"C:\Program Files (x86)\Microsoft Visual Studio 2014\Common7\IDE]tf.exe"))
        return tfPath;
    // For VS 2017 Professional version
    if (File.Exists(tfPath = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundaion\Team Explorer\Tf.exe"))
        return thPath;
    // And list all VS versions like above
    return null;
}

2)要求用户输入位置或他拥有的VS版本并生成版本(在第二个选项中还需要使用每个新的VS版本更新代码):

创建一个新的 TextBox,给一个名称(例如:)tfExeTxtBox,在您的代码中获取值:

string tfExeLoacation = tfExeTxtBox.Text;

3) 使用 TFS DLL 执行操作而不是启动tf.exe进程:

您需要 2 个 DLL(在 NuGet 中可用):

Microsoft.TeamFoundation.Client
Microsoft.TeamFoundation.VersionControl.Client

现在您可以执行所有 TFVC 操作,例如:

TfsTeamProjectcollection tfs = new TfsTeamProjectColletion(new Uri("tfs-server-url"));
VersionControlServer versionControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
Workspace workspace = versionControl.CreateWorkspace("newWorkSpace", "user name");
// Add to pending changes
workspace.PendAdd("workspace path");
var changes = workspace.GetPendingChanges();
// Check In
workspace.CheckIn(changes, "comment");

推荐阅读