4

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

Based on the 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 into browser I get correct response (file is ready to download).What I am doing wrong? Should I do authorization differently?

kendzi
  • 311
  • 2
  • 6
  • 22
  • when you logged in you are authorize to view documents. but when you want to download document via api you should prepare credential. – Navid Oct 16 '14 at 15:20
  • I did not know about it and there was no information in the documentation TC. Thanks for the advice, with Alex Maslov answer that helped a lot. – kendzi Oct 20 '14 at 13:42

1 Answers1

3

The following code achieves what you have 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've taken out the username and password and passed them to Credentials property of the WebClient instead.

I would also recommend consider guest authentication if you have your guest account enabled in TeamCity (which I do in my company). This allows you to not use any credentials at all. In this case you need to change "httpAuth" in the 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");
}

I hope this helps.

Alex Maslov
  • 413
  • 4
  • 9
  • Thanks, that works for me fine, unfortunately guest account is not an option in my company. – kendzi Oct 20 '14 at 13:39
  • http authentication isn't much harder see the answer here: http://stackoverflow.com/questions/16044313/webclient-httpwebrequest-with-basic-authentication-returns-404-not-found-for-v – James Woolfenden Oct 23 '14 at 13:36