Writing to Multiple Outputs

CodeSmith Generator lets you send the same output to multiple destinations at one time. To do this, you use the AddTextWriter method of the CodeSmith Generator Response object. This method lets you add additional TextWriter objects (or objects of any class derived from TextWriter) to the list that CodeSmith Generator renders its output to. For example, here's a template that outputs some text to two files at the same time, as well as to CodeSmith Generator 's default output window:

<%@ 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>

This technique is quite general. You could have a TextWriter that streams to a socket or to the Windows clipboard or to file or to a database or to your source code repository or to any other destination you like.

This technique is useful for generating multiple identical copies of the same file. When you need to generate multiple different files as part of a single code-generation process, you should use one sub-template for each file. Call the sub-templates from a master template and use the RenderToFile method to output each sub-template.