software-mariodiana
7/28/2015 - 3:55 PM

Simple C# example to connect to a Team Foundation Server repository and download a file from a project.

Simple C# example to connect to a Team Foundation Server repository and download a file from a project.

/*
 In addition to standard imports, you need: 
 
     System.IO;
     System.Net;

     Microsoft.TeamFoundation.Client;
     Microsoft.TeamFoundation.Framework.Common;
     Microsoft.TeamFoundation.Framework.Client;
     Microsoft.TeamFoundation.VersionControl.Client;
*/

string username = "memyselfandi";
string password = "mysecretpassword";
string repository = "https://example.visualstudio.com/DefaultCollection";

// Step 1: Obtain server via authenticated connection to project collection.

NetworkCredential nc = new NetworkCredential(username, password);
Uri uri = new Uri(repository);

TfsClientCredentials tfsCredential = new TfsClientCredentials(new BasicAuthCredential(nc));
tfsCredential.AllowInteractive = false;

TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(uri, tfsCredential);
tpc.Authenticate();

VersionControlServer vcs = tpc.GetService<VersionControlServer>();

// Step 2: Obtain item to be downloaded.

string projectName = "Top-level Folder";
string fileName = "ExampleFile.txt";

string itemPath = Path.Combine(projectName, fileName);

Item file = vcs.GetItems(String.Format(@"$/{0}", itemPath), RecursionType.None).Items.First<Item>();

// Step 3: Download item.

string destinationFolder = @"\Users\memyselfandi\Desktop";

using (Stream input = file.DownloadFile())
{
    using (FileStream fout = File.Create(Path.Combine(destinationFolder, fileName)))
    {
        input.CopyTo(fout);
    }
}