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