Writing to multiple outputs

CodeSmith Generator can send the same output to several destinations at once. Call the AddTextWriter method of the template's Response object to add a TextWriter (or an object of any class derived from TextWriter) to the list of writers that Generator renders the output to.

For example, this template writes its output to two files at the same time as the normal output window. It does so by overriding the Render method:

<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="AddTextWriter Demonstration." %>
<%@ Import Namespace="System.IO" %>
//This template demonstrates using the AddTextWriter method
//to output the template results to multiple locations concurrently.
<script runat="template">
public override void Render(TextWriter writer)
{
    StreamWriter fileWriter1 = new StreamWriter(@"C:\test1.txt", true);
    this.Response.AddTextWriter(fileWriter1);

    StreamWriter fileWriter2 = new StreamWriter(@"C:\test2.txt", true);
    this.Response.AddTextWriter(fileWriter2);

    base.Render(writer);

    fileWriter1.Close();
    fileWriter2.Close();
}
</script>

The technique is general: you can add a TextWriter that writes to a file, a socket, the clipboard, a database, your source control system or any other destination.

Note

AddTextWriter produces identical copies of the same output. To generate several different files in one run, use one sub-template per file, call the sub-templates from a master template, and output each one with RenderToFile.