Skip to content

Instantly share code, notes, and snippets.

@colinbowern
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colinbowern/bde095da68f6ee47d296 to your computer and use it in GitHub Desktop.
Save colinbowern/bde095da68f6ee47d296 to your computer and use it in GitHub Desktop.
TFS Build activity that can delete long paths such as those created by nested node.js modules.
Turns out the DeleteDirectory operation in the VB DLLs calls the Win32 APIs which is able to handle long paths:
http://stackoverflow.com/a/3282456/79842
Mind you this exposes you to a whack of Win32 quirks such as file handle / lock timing issues:
http://stackoverflow.com/a/1703799/79842
The above code tries to deal with that.
using System;
using System.Activities;
using System.IO;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Build.Activities.Extensions;
using Microsoft.TeamFoundation.Build.Workflow.Activities;
using Microsoft.VisualBasic.FileIO;
namespace CleanWorkspaceEx
{
[BuildActivity(HostEnvironmentOption.Agent)]
public sealed class CleanWorkspace : CodeActivity
{
// Define an activity input argument of type string
public InArgument<bool> Enabled { get; set; }
public InArgument<string> WorkingFolder { get; set; }
// If your activity returns a value, derive from CodeActivity<TResult>
// and return the value from the Execute method.
protected override void Execute(CodeActivityContext context)
{
if (!Enabled.Get(context)) return;
var workingFolder = WorkingFolder.Get(context) ??
context.GetExtension<IEnvironmentVariableExtension>()
.GetEnvironmentVariable<string>(context,
WellKnownEnvironmentVariables.SourcesDirectory);
if (!FileSystem.DirectoryExists(workingFolder)) return;
context.TrackBuildMessage(String.Format("Deleting working folder {0}", workingFolder));
DeleteDirectory(workingFolder);
}
public static void DeleteDirectory(string path)
{
foreach (var directory in FileSystem.GetDirectories(path))
{
DeleteDirectory(directory);
}
try
{
FileSystem.DeleteDirectory(path, DeleteDirectoryOption.DeleteAllContents);
}
catch (IOException)
{
File.SetAttributes(path, FileAttributes.Normal);
FileSystem.DeleteDirectory(path, DeleteDirectoryOption.DeleteAllContents);
}
catch (UnauthorizedAccessException)
{
File.SetAttributes(path, FileAttributes.Normal);
FileSystem.DeleteDirectory(path, DeleteDirectoryOption.DeleteAllContents);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment