Thursday, October 21, 2010

Simple MsBuild Custom Task

Here's a very simple custom task that reads in the number in a text file (which only contains a number) increments, passes it back out to the calling MsBuild, and then writes the new value to the text file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace BMsBuildTasks
  public class IncrementerTask:Task
    public ITaskItem OutputFullPath { getset; }
    public int Value { getset; }
    public override bool Execute( )
      var path =OutputFullPath==null?OutputFullPath.GetWellKnownMetaData(WellKnownMetaData35.FullPath ):
      int value;
      using (var file=new System.IO.StreamReader(path))
        if (!int.TryParse(file.ReadToEnd( ), out value))
          return false;
      using (var file=new System.IO.StreamWriter(path,false))
      OutputFullPath = new TaskItem(path);
      return true;

    public static string GetWellKnownMetaData(this ITaskItem item, WellKnownMetaData35 value)
      return item.GetMetadata(value.ToString( ));

public enum WellKnownMetaData35

No comments:

Post a Comment