tags:

views:

305

answers:

1

I don't have a great deal of experience with TFS, other than using it for source control. I am working on a C# application that will need to modify files that are being controlled by TFS. From within my C# application, how can I check out a file that is controlled via TFS?

Thanks - Randy

+2  A: 

You can use PenEdit to make your files writables, make your changes to it, then you add it to the pending changes, and finally check it in.

Here is some code where a folder structure is created and then checked in (Very similar to what you will need).

    private static void CreateNodes(ItemCollection nodes)
{
    using (var tfs = TeamFoundationServerFactory.GetServer("http://tfsserver:8080"))
    {
        var versionControlServer = tfs.GetService(typeof (VersionControlServer)) as VersionControlServer;
        versionControlServer.NonFatalError += OnNonFatalError;

        // Create a new workspace for the currently authenticated user.             
        var workspace = versionControlServer.CreateWorkspace("Temporary Workspace", versionControlServer.AuthenticatedUser);

        try
        {
            // Check if a mapping already exists.
            var workingFolder = new WorkingFolder("$/testagile", @"c:\tempFolder");

            // Create the mapping (if it exists already, it just overides it, that is fine).
            workspace.CreateMapping(workingFolder);

            // Go through the folder structure defined and create it locally, then check in the changes.
            CreateFolderStructure(workspace, nodes, workingFolder.LocalItem);

            // Check in the changes made.
            workspace.CheckIn(workspace.GetPendingChanges(), "This is my comment");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            // Cleanup the workspace.
            workspace.Delete();

            // Remove the temp folder used.
            Directory.Delete("tempFolder", true);
        }
    }
}

private static void CreateFolderStructure(Workspace workspace, ItemCollection nodes, string initialPath)
{
    foreach (RadTreeViewItem node in nodes)
    {
        var newFolderPath = initialPath + @"\" + node.Header;
        Directory.CreateDirectory(newFolderPath);
        workspace.PendAdd(newFolderPath);
        if (node.HasItems)
        {
            CreateFolderStructure(workspace, node.Items, newFolderPath);
        }
    }
}
joerage
You should not set files writable on your own. Workspace.PendEdit() does it for you. Files that are writable but not checked out represent an inconsistent state that can cause unnecessary conflicts during operations like Get and Rename.
Richard Berg
Thanks for the clarification. The post is now updated.
joerage