Skip to content

Instantly share code, notes, and snippets.

@software-mariodiana
Last active May 13, 2020 20:08
Show Gist options
  • Save software-mariodiana/e2ab5eb9a9ed4ed441f2 to your computer and use it in GitHub Desktop.
Save software-mariodiana/e2ab5eb9a9ed4ed441f2 to your computer and use it in GitHub Desktop.
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);
}
}
@AlessandroDalMas
Copy link

Hi, thanks for the code.

Have a question:
If you would perform a research of 'ExampleFile.txt' because you don't know the exact location. How would you do it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment