1.引用CodeSmith.Core.dll和CodeSmith.Engine.dll(其它依赖的,自动复制到exe目录下,见运行结果图)测试
2.编写模板,用于测试,如demo.cstui
<%@ Template Language="C#" TargetLanguage="C#" Description="Demonstrates the most basic template." %> <%@ Property Name="SampleBooleanProperty" Type="System.Boolean" Default="True" Category="Options" Description="This is a sample boolean property." %> <%@ Property Name="SampleStringProperty" Type="System.String" Default="SampleString" Category="Options" Description="This is a sample string property." %> // This class generated by CodeSmith on <%= DateTime.Now.ToLongDateString() %> public class SimpleTemplate { public SimpleTemplate() : base() { } <% if (SampleBooleanProperty) { %> private void <%= SampleStringProperty %>() { // Do something } <% } %> }
3.代码编写spa
using CodeSmith.Engine; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace CodeSmithDemo { class Program { static void Main(string[] args) { string currentPath = System.AppDomain.CurrentDomain.BaseDirectory; //模板文件,含路径 var templateName =Path.Combine(currentPath,"demo.cst"); var compiler = new CodeSmith.Engine.CodeTemplateCompiler(templateName); compiler.Compile(); if (compiler.Errors.Count == 0)//没有错误,编译成功 { var codeTemplate = compiler.CreateInstance(); codeTemplate.SetProperty("SampleStringProperty", "hello my codesmith");//给模板传递参数SampleStringProperty string csFileName = Path.Combine(currentPath,"demo.cst.cs");//输出文件名 codeTemplate.RenderToFile(csFileName, true); Console.WriteLine("compile ok!"); } else { StringBuilder sbErrors = new StringBuilder(); for (int i = 0; i < compiler.Errors.Count; i++) { sbErrors.Append(compiler.Errors[i].ToString()); } Console.WriteLine("compile error:", sbErrors.ToString()); } Console.WriteLine("end"); Console.ReadLine(); } } }
4.编译运行,结果debug
完成。
直接复制debug目录到没有安装codeSmith的另外一台pc上,能完美运行
以上测试环境为win10x64+vs2013+codeSmith7.0。code
2018年1月25日补充:blog
新装系统后仍是须要注册码,看来上次测试的系统不干净。ip