How to download Jenkins artifacts using C#

Here is a simple example of how to download Jenkins build artifact as an array of bytes using C#:

public async Task<byte[]> GetBuildArtifactAsync(Uri uri)
{
    using (var webClient = new WebClient())
    {
        var authInfo = <Jenkins Username> + ":" + <Jenkins Password>;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        webClient.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authInfo);

        ServicePointManager.SecurityProtocol =
            SecurityProtocolType.Tls |
            SecurityProtocolType.Tls11 |
            SecurityProtocolType.Tls12;

        return await
            webClient.DownloadDataTaskAsync(uri).ConfigureAwait(false);
    }
}

Change Jenkins Username and Jenkins Password accordingly.

You can use DownloadFileTaskAsync instead of DownloadDataTaskAsync if you want to download the file to the local machine.

Note: ServicePointManager.SecurityProtocol is only needed when you are accessing Jenkins via HTTPS.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s