Hey guys, I had a need for a task like Ant's replace for NAnt, so I wrote a very simple one. I'm thinking that it could be of use to others as well. Are there any chances of it getting included in the project?
I've attached the file containing the task, it builds with the latest NAntContrib from cvs if placed in the src\Tasks directory. ------------------------- Kevin Baribeau Programmer/Analyst Point2 Technologies Inc. www.point2.com ------------------------
using System.Diagnostics; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; namespace NAnt.Contrib.Tasks.Replace { /// <summary> /// A task that replaces a tokekn in a file or group of files with a new value. Loosely based on Ant's /// <a href="http://ant.apache.org/manual/CoreTasks/replace.html">replace</a> /// task. /// </summary> /// <remarks> /// This task allows you to do a batch find and replace on a set of files. For help with /// selecting files see <a href="http://nant.sourceforge.net/release/latest/help/types/fileset.html">FileSet</a> /// documentation. /// </remarks> /// <example> /// Replace 'foo' with 'bar' in all files ending in .txt in directory 'project_trunk'. /// <code> /// <![CDATA[ /// <replace token="foo" value="bar"> /// <fileset basedir="project_trunk" > /// <include name="**/*.txt" /> /// </fileset> /// </replace> /// ]]> /// </code> /// </example> [TaskName("replace")] public class ReplaceTask : Task { #region Private Instance Fields private string _token; private string _value = string.Empty; private FileSet _ReplaceFileSet; #endregion #region Public Instance Fields /// <summary> /// The piece of text to be replaced. /// </summary> [TaskAttribute("token", Required=true)] [StringValidator(AllowEmpty=false)] public string Token { get { return _token; } set { _token = value; } } /// <summary> /// The text to replace the token with. /// </summary> [TaskAttribute("value")] public string Value { get { return _value; } set { _value = value; } } /// <summary> /// The set of files in which to replace token with value. /// </summary> [BuildElement("fileset", Required=true)] public FileSet ReplaceFileSet { get { return _ReplaceFileSet; } set { _ReplaceFileSet = value; } } #endregion #region Task Overrides protected override void InitializeTask(XmlNode taskNode) { } protected override void ExecuteTask() { foreach (string file in ReplaceFileSet.FileNames) { StreamReader sr = new StreamReader(file);; string fileContents; Encoding enc = sr.CurrentEncoding; try { fileContents = sr.ReadToEnd(); } finally { sr.Close(); } StreamWriter sw = new StreamWriter(file, false, enc); try { sw.Write(enc.GetString(enc.GetBytes(fileContents.Replace(Token, Value).ToCharArray()))); } finally { sw.Close(); } } } #endregion } }