How to download artifacts from teamcity 8.1.2 using c # code

Using C # code, I would like to download artifacts (zip file) from teamcity.

Based on TC documentation ( https://confluence.jetbrains.com/display/TCD8/Accessing+Server+by+HTTP and) I wrote this code

string artifactSource = @"http://testuser:testpassword@teamcity.mydomain/httpAuth/downloadArtifacts.html?buildTypeId=ExampleBuildType&buildId=lastSuccessful";
using(WebClient teamcity = new WebClient())
{
  teamcity.DownloadFile(artifactSource, @"D:\Downloads\1.zip");
}

      

In Visual Studio I got: An unhandled exception of type "System.Net.WebException" occurred in System.dll Additional information: The remote server returned an error: (401) Unauthorized.

When I type url in the browser, I get the correct response (file ready to download). What am I doing wrong? Should I do authorization differently?

+3


source to share


1 answer


The following code gets you what you described:

var artifactSource = @"http://teamcity.mydomain/httpAuth/downloadArtifacts.html?buildTypeId=ExampleBuildType&buildId=lastSuccessful";

using (var teamcityRequest = new WebClient { Credentials = new NetworkCredential("username", "password") })
{
    teamcityRequest.DownloadFile(artifactSource, @"D:\Downloads\1.zip");
}

      

As you can see, I took the username and password and passed them to the Credentials property of the WebClient.



I would also recommend checking Guest Authentication if you have a Guest account on TeamCity enabled (which I do at my company). This allows you not to use any credentials at all. In this case, you need to change "httpAuth" in url to "guestAuth" and the code becomes

var artifactSource = @"http://teamcity.mydomain/guestAuth/downloadArtifacts.html?buildTypeId=ExampleBuildType&buildId=lastSuccessful";

using (var teamcityRequest = new WebClient())
{
    teamcityRequest.DownloadFile(artifactSource, @"D:\Downloads\1.zip");
}

      

Hope this helps.

+2


source







All Articles