How to Download the Latest Build Artifacts from Azure DevOps Programmatically in C sharp
If you are using Azure DevOps to build and deploy your applications, you may want to download the latest build artifacts from your pipelines programmatically. For example, you may want to use the build artifacts for testing, deployment, or distribution purposes.
Build artifacts are files that are produced by your build pipeline and stored in Azure DevOps. You can publish and download build artifacts using various tasks and tools in Azure DevOps, such as the Publish Build Artifacts task, the Publish Pipeline Artifacts task, the Download Build Artifacts task, the Download Pipeline Artifacts task, or the Azure CLI.
However, if you want to download the latest build artifacts from Azure DevOps programmatically using C#, you can use the Azure DevOps .NET Client Library. This is a .NET library that allows you to interact with Azure DevOps services using C# code. You can use this library to perform various operations on Azure DevOps resources, such as projects, pipelines, builds, artifacts, work items, and more.
In this blog post, we will show you how to download the latest build artifacts from Azure DevOps programmatically using C# and the Azure DevOps .NET Client Library. We will assume that you have already created a build pipeline that publishes build artifacts in Azure DevOps.
How to Install the Azure DevOps .NET Client Library
Before you can use the Azure DevOps .NET Client Library, you need to install it in your C# project. You can do this by using the NuGet Package Manager in Visual Studio. To install the Azure DevOps .NET Client Library using NuGet, follow these steps:
- Open your C# project in Visual Studio.
- Right-click on your project and select Manage NuGet Packages.
- In the Browse tab, search for Microsoft.TeamFoundationServer.Client and select it.
- In the Version dropdown, select the latest stable version and click Install.
- Accept the license agreement and wait for the installation to complete.
This will install the Azure DevOps .NET Client Library and its dependencies in your C# project and add the necessary references to your code.
How to Download the Latest Build Artifacts from Azure DevOps Programmatically
After installing the Azure DevOps .NET Client Library, you can use it to download the latest build artifacts from Azure DevOps programmatically. To do this, follow these steps:
- Create a new class file in your C# project and name it ArtifactDownloader.cs.
- Add the following using directives at the top of your class file:
1 2 3 4 5 6 7 |
using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.VisualStudio.Services.Common; using Microsoft.VisualStudio.Services.WebApi; using System; using System.IO; using System.Linq; using System.Threading.Tasks; |
- Add the following class definition and constructor to your class file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class ArtifactDownloader { private readonly string _organizationUrl; private readonly string _projectName; private readonly string _pipelineName; private readonly string _artifactName; private readonly string _outputPath; public ArtifactDownloader(string organizationUrl, string projectName, string pipelineName, string artifactName, string outputPath) { _organizationUrl = organizationUrl; _projectName = projectName; _pipelineName = pipelineName; _artifactName = artifactName; _outputPath = outputPath; } } |
This class will represent an artifact downloader that will download the latest build artifacts from a given pipeline in a given project in a given organization. The constructor will take five parameters:
- organizationUrl: The URL of your Azure DevOps organization, such as https://dev.azure.com/myorganization.
- projectName: The name of your Azure DevOps project, such as MyProject.
- pipelineName: The name of your Azure DevOps pipeline that publishes build artifacts, such as MyPipeline.
- artifactName: The name of your build artifact that you want to download, such as drop.
- outputPath: The local path where you want to save the downloaded artifact files, such as C:\Temp\Artifacts.
- Add the following method to your class file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
public async Task DownloadLatestArtifactAsync() { // Create a connection to Azure DevOps var credentials = new VssBasicCredential(string.Empty, "your-personal-access-token"); var connection = new VssConnection(new Uri(_organizationUrl), credentials); // Get a reference to the build client var buildClient = connection.GetClient // Get a list of builds for the specified pipeline var builds = await buildClient.GetBuildsAsync(_projectName, definitions: new[] { _pipelineName }); // Get the latest completed build var latestBuild = builds.OrderByDescending(b => b.FinishTime).FirstOrDefault(b => b.Status == BuildStatus.Completed); // Check if the latest build exists and has the specified artifact if (latestBuild != null && await buildClient.HasArtifactAsync(_projectName, latestBuild.Id, _artifactName)) { // Get the artifact var artifact = await buildClient.GetArtifactAsync(_projectName, latestBuild.Id, _artifactName); // Check if the artifact is of type container if (artifact.Resource.Type == "container") { // Get a reference to the file container client var fileContainerClient = connection.GetClient // Get the artifact files var artifactFiles = await fileContainerClient.GetItemsAsync(artifact.Resource.Data, scope: "build"); // Download each file to the output path foreach (var file in artifactFiles) { // Skip directories if (file.ItemType == ContainerItemType.Folder) { continue; } // Create the local file path var localFilePath = Path.Combine(_outputPath, file.Path.TrimStart('/')); // Create the local directory if it does not exist var localDirectory = Path.GetDirectoryName(localFilePath); Directory.CreateDirectory(localDirectory); // Download the file Console.WriteLine($"Downloading {file.Path} to {localFilePath}..."); using (var fileStream = new FileStream(localFilePath, FileMode.Create)) { await fileContainerClient.DownloadFileAsync(file.ContainerId, file.Path, fileStream, scope: "build"); } } } else { Console.WriteLine($"The artifact {artifact.Name} is not of type container and cannot be downloaded."); } } else { Console.WriteLine($"The latest build of {pipelineName} does not have the artifact {artifactName}."); } } |
This method will download the latest build artifacts from Azure DevOps programmatically using the Azure DevOps .NET Client Library. It will perform the following steps:
- Create a connection to Azure DevOps using a personal access token. You can create a personal access token in your Azure DevOps profile settings. Make sure to grant the appropriate scopes for your token, such as Build (Read) and Packaging (Read).
- Get a reference to the build client, which is a service that allows you to interact with build resources in Azure DevOps.
- Get a list of builds for the specified pipeline and sort them by finish time in descending order.
- Get the latest completed build from the list and check if it has the specified artifact.
- Get the artifact and check if it is of type container. A container is a type of artifact that stores files in a hierarchical structure.
- Get a reference to the file container client, which is a service that allows you to interact with file containers in Azure DevOps.
- Get the artifact files from the file container and iterate over them.
- Download each file to the output path, creating the local directories if they do not exist.
- Add a main method to your class file or another class file to test your artifact downloader. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
static async Task Main(string[] args) { // Create an instance of the artifact downloader with your parameters var downloader = new ArtifactDownloader( organizationUrl: "https://dev.azure.com/myorganization", projectName: "MyProject", pipelineName: "MyPipeline", artifactName: "drop", outputPath: @"C:\Temp\Artifacts" ); // Download the latest artifact await downloader.DownloadLatestArtifactAsync(); } |
- Run your C# project and check the output path for the downloaded artifact files.
Conclusion
In this blog post, we have shown you how to download the latest build artifacts from Azure DevOps programmatically using C# and the Azure DevOps .NET Client Library. We have explained what build artifacts are and how to publish and download them using various tasks and tools in Azure DevOps. We have also shown you how to use the Azure DevOps .NET Client Library to interact with Azure DevOps services using C# code. We hope this post has been helpful and informative for you. If you have any questions or feedback, please leave a comment below.