Download workitem attachments from TFS (files corr

2019-09-05 02:18发布

问题:

I am trying to create C# code, so I can automatically download all attachments for predefined query of BUGS from Team Foundation Server. The code seems to work just fine, yet all downloaded files are for an unexpected reason corrupted and I cannot view them. Could someone please take a look at the code and share an opinion? Many thanks for the help!

static void Main()
        {
            // Connection to the Team Project Collection
            TfsTeamProjectCollection tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
              new Uri("https://xxx.visualstudio.com/defaultcollection"));

            // Get a WorkItemStore object for the Team Project Collection.
            WorkItemStore workItemStore = new WorkItemStore(tpc);

            // Run a query.
            WorkItemCollection queryResults = workItemStore.Query(
              @"SELECT *
    FROM WorkItems
    WHERE [System.WorkItemType] = 'Bug'
    AND [Language] = 'xxx'
    AND [How Found] = 'xxx'
    AND [Assigned to] = 'xxx'
    ORDER BY [Changed Date] DESC");

            // Get a WebClient object to do the attachment download
            WebClient webClient = new WebClient()
            {
                UseDefaultCredentials = true
            };

            // Loop through each work item.
            foreach (WorkItem workItem in queryResults)
            {
                // Loop through each attachment in the work item.
                foreach (Attachment attachment in workItem.Attachments)
                {
                    // Construct a filename for the attachment
                    string filename = string.Format("C:\\TEST\\{0}_{1}", workItem.Fields["ID"].Value, attachment.Name);
                    // Download the attachment.
                    webClient.DownloadFile(attachment.Uri, filename);
                }
            }

回答1:

This is caused by the WebClient didn't authenticate to TFS server correctly. Instead of using WebClient to download the file, you can use WorkItemServer.DownloadFile() method in Microsoft.TeamFoundation.WorkItemTracking.Proxy to download the file. Refer to the code below for details:

foreach (Attachment atm in workItem.Attachments)
            {
                WorkItemServer wise = tpc.GetService<WorkItemServer>();
                string file = wise.DownloadFile(atm.Id);
                File.Copy(file,"C:\\TEST\\" + atm.Name,true);

            }


回答2:

For the authentication, you can add below code to authenticate the project collection level.

//get credentials by logging in with a user interface
var credentialsProvider = new UICredentialsProvider();

var teamProjectCollection = new TfsTeamProjectCollection(collection, credentialsProvider);
teamProjectCollection.Authenticate();

More details please refer this blog: Team Foundation Service: Downloading attachments from work items through the api



标签: c# tfs