1

I have a powershell script that does this :

    $uri = "$($tfsUri)/$($teamproject)/_apis/build/builds/$($buildID)?api-version=2.0"
    $data = @{keepForever = $keepForever} | ConvertTo-Json
    $response = $webclient.UploadString($uri,"PATCH", $data) 

I'm trying to rewrite this in C#, using a Webclient.

WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
string reply = client.UploadString(url, "keepForever = true");
Console.WriteLine(reply);

But I get : The remote server returned an error: (401) Unauthorized.

This is TFS 2015 VNext, if that helps.

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
JL.
  • 78,954
  • 126
  • 311
  • 459

2 Answers2

9

You are missing the METHOD in your call to UploadString.

string reply = client.UploadString(url, "keepForever = true");

should be:

string reply = client.UploadString(url, "PATCH", "keepForever = true");

A 401 is unauthorised, so also see if there is a step before in your Powershell where you are logging in or joining a session, you would need to replicate that in your C#.

Murray Foxcroft
  • 12,785
  • 7
  • 58
  • 86
2

In order to send a PATCH request you can use WebClient.UploadData.

string data = "keepForever = true";
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
string reply = client.UploadData(url, "PATCH", System.Text.Encoding.UTF8.GetBytes(data));
Console.WriteLine(reply);
Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
  • One correction on the `string reply` line of code: client.UploadData [returns](https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.uploaddata?view=netframework-4.5.2#System_Net_WebClient_UploadData_System_String_System_Byte___) a `byte[]`, not string. – Michael Aug 16 '21 at 19:48