Programmatically Download Attachments from TFS

Home / Code Snippet / Programmatically Download Attachments from TFS

I created this short snippet of code the other day in reference to a forum question on how to retrieve the linked items for a given work item.  The code below uses the TFS Object Model to retrieve a specific work item (in this case, item #16) and save all attachments to the local file system.

Code Snippet
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System;
using System.IO;

namespace DTTFSLib
{
public class WorkItemTest
{
public WorkItemTest(string serverName)
{
// Connect to the desired Team Foundation Server
TeamFoundationServer tfsServer = new TeamFoundationServer(serverName);

// Authenticate with the Team Foundation Server
tfsServer.Authenticate();

// Get a reference to a Work Item Store
WorkItemStore workItemStore = new WorkItemStore(tfsServer);

// Retrieve a Work Item by ID - in this case, bug #16
WorkItem workItem = workItemStore.GetWorkItem(16);

// Get attachments
if (workItem != null)
{
System.Net.
WebClient request = new System.Net.WebClient();

// NOTE: If you use custom credentials to authenticate with TFS then you would most likely
// want to use those same credentials here
request.Credentials = System.Net.CredentialCache.DefaultCredentials;

foreach (Attachment attachment in workItem.Attachments)
{
// Display the name & size of the attachment
Console.WriteLine("Attachment: '" + attachment.Name + "' (" + attachment.Length.ToString() + " bytes)");

// Save the attachment to a local file
request.DownloadFile(attachment.Uri, Path.Combine(@"C:\Attachments", attachment.Name));
}
}
}
}
}

 

Note that exception handling and custom authentication have been left out for brevity.

Check out the Essentials of Work Item Object Model MSDN site for more information on the work item object model.

  • Anonymous

    this will not work with team foundation service under certain conditions, but anyway, good article

ContactUs.com