Team Foundation Version Control client API example for TFS 2010 and newer

Over six years ago, I posted a sample on how to use the version control API.  The API changed in TFS 2010, but I hadn’t updated the sample.  Here is a version that works with 2010 and newer and is a little less aggressive on clean up in the finally block.

This is a really simple example that uses the version control API.  It shows how to create a workspace, pend changes, check in those changes, and hook up some important event listeners.  This sample doesn't do anything useful, but it should get you going.

You have to supply a Team Project as an argument.

The only real difference in this version is that it uses the TeamFoundationServer constructor (in beta 3, you were forced to use the factory class).

You'll need to add references to the following TFS assemblies to compile this example.


Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Text;
  6. using Microsoft.TeamFoundation.Client;
  7. using Microsoft.TeamFoundation.VersionControl.Client;
  9. namespace BasicSccExample
  10. {
  11.     class Example
  12.     {
  13.         static void Main(string[] args)
  14.         {
  15.             // Verify that we have the arguments we require.
  16.             if (args.Length < 2)
  17.             {
  18.                 String appName = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
  19.                 Console.Error.WriteLine("Usage: {0} collectionURL teamProjectPath", appName);
  20.                 Console.Error.WriteLine("Example: {0} http://tfsserver:8080/tfs/DefaultCollection $/MyProject", appName);
  21.                 Environment.Exit(1);
  22.             }
  24.             // Get a reference to our Team Foundation Server.
  25.             TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(args[0]));
  27.             // Get a reference to Version Control.
  28.             VersionControlServer versionControl = tpc.GetService<VersionControlServer>();
  30.             // Listen for the Source Control events.
  31.             versionControl.NonFatalError += Example.OnNonFatalError;
  32.             versionControl.Getting += Example.OnGetting;
  33.             versionControl.BeforeCheckinPendingChange += Example.OnBeforeCheckinPendingChange;
  34.             versionControl.NewPendingChange += Example.OnNewPendingChange;
  36.             // Create a workspace.
  37.             Workspace workspace = versionControl.CreateWorkspace("BasicSccExample", versionControl.AuthorizedUser);
  39.             String topDir = null;
  41.             try
  42.             {
  43.                 String localDir = @"c:\temp\BasicSccExample";
  44.                 Console.WriteLine("\r\n--- Create a mapping: {0} -> {1}", args[1], localDir);
  45.                 workspace.Map(args[1], localDir);
  47.                 Console.WriteLine("\r\n--- Get the files from the repository.\r\n");
  48.                 workspace.Get();
  50.                 Console.WriteLine("\r\n--- Create a file.");
  51.                 topDir = Path.Combine(workspace.Folders[0].LocalItem, "sub");
  52.                 Directory.CreateDirectory(topDir);
  53.                 String fileName = Path.Combine(topDir, "basic.cs");
  54.                 using (StreamWriter sw = new StreamWriter(fileName))
  55.                 {
  56.                     sw.WriteLine("revision 1 of basic.cs");
  57.                 }
  59.                 Console.WriteLine("\r\n--- Now add everything.\r\n");
  60.                 workspace.PendAdd(topDir, true);
  62.                 Console.WriteLine("\r\n--- Show our pending changes.\r\n");
  63.                 PendingChange[] pendingChanges = workspace.GetPendingChanges();
  64.                 Console.WriteLine("  Your current pending changes:");
  65.                 foreach (PendingChange pendingChange in pendingChanges)
  66.                 {
  67.                     Console.WriteLine("    path: " + pendingChange.LocalItem +
  68.                                       ", change: " + PendingChange.GetLocalizedStringForChangeType(pendingChange.ChangeType));
  69.                 }
  71.                 Console.WriteLine("\r\n--- Checkin the items we added.\r\n");
  72.                 int changesetNumber = workspace.CheckIn(pendingChanges, "Sample changes");
  73.                 Console.WriteLine("  Checked in changeset " + changesetNumber);
  75.                 Console.WriteLine("\r\n--- Checkout and modify the file.\r\n");
  76.                 workspace.PendEdit(fileName);
  77.                 using (StreamWriter sw = new StreamWriter(fileName))
  78.                 {
  79.                     sw.WriteLine("revision 2 of basic.cs");
  80.                 }
  82.                 Console.WriteLine("\r\n--- Get the pending change and check in the new revision.\r\n");
  83.                 pendingChanges = workspace.GetPendingChanges();
  84.                 changesetNumber = workspace.CheckIn(pendingChanges, "Modified basic.cs");
  85.                 Console.WriteLine("  Checked in changeset " + changesetNumber);
  86.             }
  87.             finally
  88.             {
  89.                 if (topDir != null)
  90.                 {
  91.                     Console.WriteLine("\r\n--- Delete all of the items under the test project.\r\n");
  92.                     workspace.PendDelete(topDir, RecursionType.Full);
  93.                     PendingChange[] pendingChanges = workspace.GetPendingChanges();
  94.                     if (pendingChanges.Length > 0)
  95.                     {
  96.                         workspace.CheckIn(pendingChanges, "Clean up!");
  97.                     }
  99.                     Console.WriteLine("\r\n--- Delete the workspace.");
  100.                     workspace.Delete();
  101.                 }
  102.             }
  103.         }
  105.         internal static void OnNonFatalError(Object sender, ExceptionEventArgs e)
  106.         {
  107.             if (e.Exception != null)
  108.             {
  109.                 Console.Error.WriteLine("  Non-fatal exception: " + e.Exception.Message);
  110.             }
  111.             else
  112.             {
  113.                 Console.Error.WriteLine("  Non-fatal failure: " + e.Failure.Message);
  114.             }
  115.         }
  117.         internal static void OnGetting(Object sender, GettingEventArgs e)
  118.         {
  119.             Console.WriteLine("  Getting: " + e.TargetLocalItem + ", status: " + e.Status);
  120.         }
  122.         internal static void OnBeforeCheckinPendingChange(Object sender, ProcessingChangeEventArgs e)
  123.         {
  124.             Console.WriteLine("  Checking in " + e.PendingChange.LocalItem);
  125.         }
  127.         internal static void OnNewPendingChange(Object sender, PendingChangeEventArgs e)
  128.         {
  129.             Console.WriteLine("  Pending " + PendingChange.GetLocalizedStringForChangeType(e.PendingChange.ChangeType) +
  130.                               " on " + e.PendingChange.LocalItem);
  131.         }
  132.     }
  133. }

Comments (53)

  1. Anonymous says:

    This was MOST helpful!! Now we can directly save files processed via SSIS to TFS for version control!

    Thank a BUNCH!

  2. Anonymous says:

    I'm getting this exception while running the sample code:

    Could not load file or assembly 'file:///C:TfsAppbinMicrosoft.WITDataStore.dll' or one of its dependencies. The module was expected to contain an assembly manifest.

    Exception Details: System.BadImageFormatException: Could not load file or assembly 'file:///C:TfsAppbinMicrosoft.WITDataStore.dll' or one of its dependencies. The module was expected to contain an assembly manifest.

    Any ideas?

  3. Buck Hodges says:

    Hrusi, my guess it would be due to how the code is being built. It's been a while since I've messed with it, but check AnyCPU vs. x86.

  4. Anonymous says:

    Hi, I am getting no pendingchanges in my console app. I had same issue with web app, I tried the same code on web form application where it worked. I thought it has to do with IIS permissions evenhugh i am passing different credential object to create TfsTeamProjectCollectio..

  5. Buck Hodges says:

    Veena, I'd recommend running it under a debugger and stepping through the code to see what's going wrong.

  6. Anonymous says:

    i have a file which is created by taking a backup of tables,this file i need to checkin to tfs 2010.

    so how this can be done.

  7. Buck Hodges says:

    Vikram, if it's a file on disk, then you can pend an add on it and check it in. The sample code shows both pending an add and checking in.

  8. Anonymous says:

    Hi Buck, I really need your help, whenever a do a checkout on a file and the try to write changes to it using StreamWriter I get "The process cannot access the file because it is being used by another process"

  9. Anonymous says:

    Nevermind! I found the issue :P. Before calling the writer I had an open stream of the file

  10. Hi, I tried the same code but when i call  workspace.CheckIn(pendingChanges, "Sample changes"); I am getting "No files checked in error" Could you please tell me what could be the issue is?

  11. Buck Hodges says:

    Vidhya, make sure your pending changes array has your pending changes listed in it and make sure a file has changed.

  12. Buck, I have the two pending changes and also the basic.cs has been added with the line. I am not sure what could be the issue now?

  13. Anonymous says:

    I am exactly doing what is reffered in above sample code. But not getting any Pending changes to checkin.

    Looking for a help, it is an wep app. When running the applicaiton with Development server, every thing works fine. But as soon as we deploy it on IIS, pending changes can not be fteched.

    Request for an immediate help, if anyone encounter this problem and resolved.

    Thanks in advance.

  14. Anonymous says:

    Whenever I get to workspace.CheckIn, I receive the following error:

    err.Message = "TF204000: The Team Foundation Server for this workspace does not support one or more of the checkin options you have selected."

    Any help would be greatly appreciated.

  15. Buck Hodges says:

    Allan, are the server and client different versions (e.g., one is 2010 and the other 2012)? Are you explicitly specifying any checkin options?

  16. Anonymous says:

    Im getting an error when installing my tfs api on client machine .Microsoft.widatastore.dll missing without visual studio installed rather than the latter on dev machine.Is this due to not having visual studio installed because im accessing tfs server through api what could be the issue.Any ideas anyone?

  17. Buck Hodges says:

    Tahir, you need one of the following installed:

    That will provide the required DLLs.

  18. Tman558 says:


  19. Tman558 says:

    Hi EveryOne,

    I have a tfs api. A user logs in and i want his valid projects that he has permissions too.So i can put it in a combo box to choose from and area and iterations etc. Does anyone know of a way.

  20. Buck Hodges says:

    If you want to make requests to TFS as another user, you would need to use impersonation. In the future when we have OAuth support, that would be a better way to go.…/introducing-tfs-impersonation.aspx

  21. Tman558 says:


  22. Anonymous says:

    Hi Buck, Its a very helpful code, but I am facing an issue. I have mapped the workspace with local folder.

    I am trying to get latest using workspace, it works fine. but when I deployed it to IIS on  development server. Some time it takes ages to download and does not throw and error. I has fine downloaded in partial document format. Can you tell him why this kind of behaviour.

    Any input appreciated. Below is simple sample code used.

    GetRequest request = new GetRequest(new ItemSpec(path, RecursionType.Full), VersionSpec.Latest);

    status = Workspace.Get(request, GetOptions.Overwrite);

  23. Anonymous says:

    Folder size which I download are any where from 10 MB to 30 MB. There are some partial downloaded file, which my give you some clue

  24. Buck Hodges says:

    Rajesh, when running under IIS, make sure that the user under which it runs has sufficient privileges and there is enough disk space. Also, make sure that user has a Windows profile and access to the temp directory (all files downloaded first go to the temp folder and then are copied to the ultimate destination). It's those sorts of things that tend to cause problems under IIS.

  25. Anonymous says:

    I have a windows profile and also access to temp dir. I am able to download most of the time. Bu some times while downloading "when the code calls  Workspace.Get() It keeps on  loading. and does not even throw an error. Is there a way I  can find what could be the issue.

  26. Buck Hodges says:

    Rajesh, your best bet would be to attach a debugger and have it break on exceptions to see where the problem is (assuming that the problem involves an exception). If not, then after it hangs for a while, break on it and see what it's waiting on.

  27. Anonymous says:

    Hello Buck,

    Is it possible to capture a Check-In that happens in TFS and trigger off an action based on that.

    Lets say I build a Windows Service or a Console App that monitors a particular Project in TFS and on Check-In on any of the files inserts a record in a SQL DB table with the name of the file, class and method that was modified?

  28. Buck Hodges says:

    Jaideep, if you are looking to do this on the server, I'd suggest a server-side plugin where you could do it in .NET. This book has details:…/ref=la_B004AR91MM_1_1.

    If you are looking to do this on Visual Studio Online, check out Service Hooks:…/get-started-service-hooks-creating-and-managing-vsi.

    Regardless, please don't do anything in SQL. It would put your server in an unsupported state.

  29. Anonymous says:

    Hi Buck,

    Thanks for posting this code!  I'm working on automating the checking in of code on a server and am having trouble capturing the pending changes.  I was able to create a local workspace, map folders, and do a get latest in code.  However, when a change is made to a file on the local folder, it is not getting picked up with "workspace.GetPendingChanges()".  I even tried "workspace.PendEdit(workspacePath, RecursionType.Full)" before calling GetPendingChanges() to no avail.  This code seems to work fine on my development machine.

    One difference between the dev and prod machines are I have VS 2012 installed on my dev machine, but just copied the Microsoft.TeamFoundation.*.dll's (.Client; .Common; .VersionControl.Client; TeamFoundation) to the server.  Do I need team explorer or something else installed on the server or is there a way to force the pending changes to get picked up?


  30. Buck Hodges says:

    Josh, that last detail about copying the dlls, that's definitely a problem (and likely the root cause of it not working on the server). You can install Team Explorer on the server or you can install the TFS Object Model, which is even smaller. You can use 2013 or 2012, based on what you need. Here's the link to the 2013 version:

  31. Anonymous says:

    Thanks Buck!  That seemed to do the trick.

  32. Buck Hodges says:

    Josh, glad to hear it!

  33. Anonymous says:

    Hi Buck,

    I am getting an error while check-in code using api code. But I am getting this error. Did not found any once facing the issue. There is no documentation on why this error thrown by TFS Version control client.

    TF14054: The Encoding -2 is not valid. The client should never send this value

  34. Buck Hodges says:

    Rajesh, if I recall correctly that means that the client OM didn't set the encoding. I can't say I remember any case like that. Are you using the code in this blog post or something else?

    Here's a blog post on encoding detection that we do:…/463281.aspx.

  35. Anonymous says:

    I am using the code mentioned in the above code given by you. "workspace.PendAdd(topDir, true);". This method throws the error "TF14054: The Encoding -2 is not valid. The client should never send this value".

    Although the above code works fine on local. It fails when I upload the project on development server.Development server is Windows server 2012 and local has windows 7. Is there any dependency on OS or  Is there any dll the required might not present.  I have below dll on project bin folder

    1. Microsoft.TeamFoundation.Client.dll
    2. Microsoft.TeamFoundation.Common.dll

    3. Microsoft.TeamFoundation.VersionControl.Client.dll

    4 Microsoft.TeamFoundation.VersionControl.Common.dll

    1. Microsoft.TeamFoundation.WorkItemTracking.Client.DataStoreLoader.dll

    Please help me out with this issue. Kind of killing me.:)

  36. Anonymous says:

    Adding to above question, what can be done if TFS  did not detect the encoding properly. Can we set it manually. But again the question is if I need to set it manually I need to find the encoding :)

  37. Anonymous says:

    Hi Buck,

    I solved the problem, I installed the OM on server and it worked. I went through couple of question you answered and fixed it.

    Thanks a lot for your efforts for helping people use TFS and TFS API. Is there any good book for TFS API. Wanted to do some mastering on that.

  38. Buck Hodges says:

    Rajesh, I'm glad you got it fixed. The professional TFS book by Holliday and others is good and talks about writing apps with the client OM.

  39. Anonymous says:

    thanks for the example, it is always easier to see things actually used than from the documentation.

  40. Anonymous says:

    Very useful. Interesting.

    IMHO, for minimize learning curve, better a good unit test Method that Console Application.

    What's is best patterns and practices for unit testing using TeamFoundationClient (TFS API)?.

    I use VS 2012 and TFS 2008.

    I think in unit test like this:

    Include file in Source Control

    Check Out

    Check In

    Create Branch


    Delete Branch


    public class TfsTests



       public void TestMethod1()


           var serverUrl = "tsfserver";

           var tfs = new TeamFoundationServer(serverUrl);

           var vcServer = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));

           // Code here



    IMHO, the more complete unit test like this:

    Create Team Project

    Create WorkSpace

    Mapping local folder for Workspace

    Include files in Source Control (in those Workspace and TeamProject)

    Check Out file

    Check In file

    Create Branch

    View History


    View History

    Delete Branch

    Delete Mappings

    Delete WorkSpace

    Delete Team Project

    Any suggestions about it ? Maybe share source code about all in github, and share it for all Community.

  41. Buck Hodges says:

    It's a good suggestion. We always need more examples of how to use the API.

  42. abdel says:

    Hi buck,

    what is the arguments in a Main??

  43. Michael Day says:

    Thanks, Buck! We use a SharedAsemblyInfo.cs versioning scheme(…/shared-assembly-info-in-visual-studio-projects.aspx), and with a little tweaking, I was able to use this to successfully update our file versions prior to building.

  44. Buck Hodges says:

    Michael, glad to hear it. Your comment also reminded me to add an update do this post about our new NuGet packages for the client object model.

  45. Milos says:


    Whenever I get to workspace.CheckIn, I receive the following error:

    err.Message = "TF204000: The Team Foundation Server for this workspace does not support one or more of the checkin options you have selected."

    Any help would be greatly appreciated.

    I am not using any checkin options or setting them whatsoever. The problem is that my version of Microsoft.TeamFoundation.Client is from VS2012 but if I use VS2010 dll this problem is solved. Is there a way to avoid loading multiple dll since I am using different versions of TFS server? Btw when checking in from VS2012 to the server it works without any problems.

  46. Milos says:

    I was able to resolve previous problem with:

    WorkspaceCheckInParameters workspaceCheckInParameter = new WorkspaceCheckInParameters(changes, comment);


  47. Ryan says:

    Thanks for your details.But I am wrking in an organisation.Need to connect to the organisation TFS which having crdentials programatically.TFS server is 2012 .Will the above code work for my requirement

  48. Anderson says:

    Hi Buck!! All ok with you?
    I am with one problem.
    When i will make check in, i get this error:
    TF10141: No files checked: Resolve conflicts and try again.

    I want keep ever local version in TFS.
    You have some sugestion to help me?

    1. Buck Hodges says:

      Anderson, that means there’s a newer version on the server. You would need to resolve the conflict.

      1. Anderson says:

        finally worked
        Thanks for help.

  49. Hi Buck Hodges,
    Good article,
    But i´m getting this error :
    “result”: null,
    “StatusCd”: null,
    “StatusTxt”: “System.Web.Services.Protocols.SoapException: Server was unable to process request. —> System.TypeLoadException: Could not load type ‘Microsoft.TeamFoundation.Client.BasicAuthCredential’ from assembly ‘Microsoft.TeamFoundation.Client, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’.\n at wbsTFS.UpdateBugs(String url, String IDProject)\n — End of inner exception stack trace —”

    I´m using this to invoke a webserver to update bugs and user stories from tfs as service but i get that error.
    You know about possible solutions

  50. Lakshmi says:

    workspace.penadd not working…Adding folder not reflecting in TFS server

Skip to main content