Search code examples
c#azure-devopstfsazure-devops-services.net-sdk

How to download files from Azure DevOps using TfvcHttpClient


I would like to download the latest version of all files from one of my Azure Dev Ops code-repository directories using the TfvcHttpClient class. Unfortunately, this is not documented very good, nor can i find useful example programs.

What i have got so far ist this:

var creds = new VssBasicCredential(string.Empty, "PAT_GOES_HERE");
var connection = new VssConnection(new  Uri("https://username.visualstudio.com/DefaultCollection"), creds);
using var tfsClient = connection.GetClient<TfvcHttpClient>();

var result = tfsClient.GetItemsBatchZipAsync(new TfvcItemRequestData() {ItemDescriptors = new []{new TfvcItemDescriptor(){Path="/", RecursionLevel = VersionControlRecursionType.Full,VersionType = TfvcVersionType.Latest}} }, "Testcases").Result;
var fs = File.Create("c:\\temp\\x.zip");
result.CopyTo(fs);

The file gets created with size 0, but no bytes are copied and CopyTo() does not return.

How would i download the latest version of a directory?


Solution

  • Here is a complete solution that works with the current version of the .net libraries (16.205.1).

    using System.IO.Compression;
    using Microsoft.TeamFoundation.SourceControl.WebApi;
    using Microsoft.VisualStudio.Services.Common;
    using Microsoft.VisualStudio.Services.WebApi;
    
    namespace GetCurrent
    {
        internal class Program
        {
            private static readonly string DevOpsPat = Environment.GetEnvironmentVariable("DIE_DEVOPS_PAT") ?? throw new InvalidOperationException("DIE_DEVOPS_PAT");
            private const string DestinationDirectory = "c:\\temp\\testcases";
    
            static void Main()
            {
                var credentials = new VssBasicCredential(string.Empty, DevOpsPat);
                var connection = new VssConnection(new Uri("https://twoelfer.visualstudio.com/DefaultCollection"), credentials);
    
                using var tfsClient = connection.GetClient<TfvcHttpClient>();
    
                var zip = Path.GetTempFileName();
                using var stream = File.Create(zip);
                using var item = tfsClient.GetItemZipAsync( "$/Testcases" ).Result;
                item.CopyTo(stream);
                stream.Close();
                try
                {
                    ZipFile.ExtractToDirectory(zip, DestinationDirectory);
                    File.Delete(zip);
                }
                catch
                {
                    throw new Exception("Unable to unzip the file: " + zip);
                }
            }
        }
    }