Reputation: 17
String Filepath = Txt_Attachfile.Text;
string accesToken = ConfigurationManager.AppSettings["AccessToken"];
var u = new Uri("https://abc.visualstudio.com/");
VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.VssBasicCredential(string.Empty, accesToken));
var connection = new VssConnection(u, c);
var workItemTracking = connection.GetClient<WorkItemTrackingHttpClient>();
string patchcontent = "";
JsonPatchDocument patchDocument = new JsonPatchDocument();
if (Txt_Attachfile.Text != "")
{
string filename = Path.GetFileName(Txt_Attachfile.Text);
Attachemt attachment = new Attachemt();
attachment = UpdloadToStore(filename);
patchDocument.Add(new JsonPatchOperation()
{
Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Add,
Path = "/relations/-",
Value = new
{
rel = "AttachedFile",
url = attachment.url,
attributes = new
{
comment = "VanDelay Industries - Spec"
}
}
});
var result = workItemTracking.UpdateWorkItemAsync(patchDocument, Convert.ToInt32(workitem));
patchcontent = JsonConvert.SerializeObject(result);
}
On accounts with higher attachment upload limits (>130MB), you will need to used "chunked" upload to upload your file. First, register your chunked upload by doing the following:
Upvotes: 1
Views: 613
Reputation: 38136
Since the file to add a a work item attachment is 10MB (<130MB), you should use the REST API as the way to upload a text file instead of chunked upload REST API.
And an example code to upload a file to VSTS and add the file as an attachment for a work item as below:
int id=12;
string filename = @"C:\path\to\the\upload\file";
Uri accountUri = new Uri("https://account.visualstudio.com");
String personalAccessToken = "PAT";
VssConnection connection1 = new VssConnection(accountUri, new VssBasicCredential(string.Empty, personalAccessToken));
WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>();
Console.WriteLine("Attempting upload of: {0}", "");
AttachmentReference attachment = workItemTrackingClient.CreateAttachmentAsync(filename).Result;
Console.WriteLine(attachment.Id);
Console.WriteLine(attachment.Url);
BuildHttpClient buildClient = connection.GetClient<BuildHttpClient>();
WorkItemTrackingHttpClient workItemTrackingClient1 = connection.GetClient<WorkItemTrackingHttpClient>();
JsonPatchDocument patchDocument = new JsonPatchDocument
{
new JsonPatchOperation()
{
Operation = Operation.Add,
Path = "/relations/-",
Value = new
{
rel = "AttachedFile",
url = attachment.Url,
attributes = new { comment = "VanDelay Industries - Spec" }
}
}
};
WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result;
Console.WriteLine("succeed!");
Upvotes: 2