调用codeSmith API,l动态编译cst文件,生成exe文件可以在目前pc免安装codeSmith


1.引用CodeSmith.Core.dll和CodeSmith.Engine.dll(其它依赖的,自动复制到exe目录下,见运行结果图)


2.编写模板,用于测试,如demo.cst

<%@ 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.代码编写

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目录到没有安装codeSmith的另一台pc上,能完美运行
以上测试环境为win10x64+vs2013+codeSmith7.0。

 

2018年1月25日补充:

新装系统后还是需要注册码,看来上次测试的系统不干净。

posted on 2018-01-10 08:21  pw33  阅读(205)  评论(0编辑  收藏  举报

导航