看到百度上有同志在搜索“CodeSmith输出目录”,偶正好会,就写篇经验帖,于需要的朋友可以共享下经验。

    要CodeSmith生成完代码可以自动保存到某个目录,一般需要让自己的模板继承CodeSmith类库中的OutputFileCodeTemplate类。

    C#脚本示例代码如下:

CodeSmith自动保存输出结果using System;
CodeSmith自动保存输出结果
using
 System.Text;
CodeSmith自动保存输出结果
using
 System.ComponentModel;
CodeSmith自动保存输出结果
using
 CodeSmith.Engine;
CodeSmith自动保存输出结果
using
 System.Data;
CodeSmith自动保存输出结果
using
 SchemaExplorer;
CodeSmith自动保存输出结果
using
 CodeSmith.BaseTemplates;
CodeSmith自动保存输出结果
CodeSmith自动保存输出结果
public class
 TestTemplate : OutputFileCodeTemplate
}

    编写完这个模板的脚本后我们需要把我们的模板与这个脚步关联起来。

    先将上面的代码保存到TestTemplates.cst.cs文件,然后编写一下模板:

CodeSmith自动保存输出结果<%@ CodeTemplate Language="C#" TergetLanguage="C#" src="TestTemplates.cst.cs" Inherits="TestTemplate" %>
CodeSmith自动保存输出结果
<%@ Assembly Name="SchemaExplorer" %>
CodeSmith自动保存输出结果
<%@ Assembly Name="System.Data" %>
CodeSmith自动保存输出结果
<%@ Assembly Name="CodeSmith.BaseTemplates" %>
CodeSmith自动保存输出结果
<%@ Import Namespace="SchemaExplorer" %>
CodeSmith自动保存输出结果
<%@ Import Namespace="System.Data" %>
CodeSmith自动保存输出结果
<%@ Property Name="FoldName" Type="System.String" Default="D:\\GeneratorCode" %>
CodeSmith自动保存输出结果
<%=Hello()%>
CodeSmith自动保存输出结果
<% if(!System.IO.Directory.Exists(FoldName)) System.IO.Directory.CreateDirectory(FoldName); %>
CodeSmith自动保存输出结果
<% this.OutputFile = FoldName + "\\" + "Hello.cs"; %>
CodeSmith自动保存输出结果
<% System.Diagnostics.Process.Start(FoldName); %>

    模板第一句就是用于关联模板与脚本文件的了,接下来是引入我们用到的CodeSmith类库的程序集,还有Import在脚本中using的.NET命名空间,然后那个Property就是我们的输出目录,默认值是D:\GeneratorCode,这个属性会出现在CodeSmith的属性栏里到时候我们可以根据需要改,用过的人应该都知道,呵呵。
   
    中间调用Hello函数就不用说了,后面2句脚本就是我用于保存文件的代码了,先判断目录存在不存在,不存在创建目录,然后保存文件。最后一句用于弹出Explorer查看代码目录。

    呵呵,本文到此结束,是不是很简单~~如果大家有什么更好的方式希望可以交流交流。

相关文章:

  • 2022-12-23
  • 2021-09-13
  • 2021-05-23
  • 2021-06-29
  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-25
  • 2022-02-17
  • 2022-12-23
  • 2022-12-23
  • 2021-07-04
  • 2021-08-03
  • 2022-12-23
相关资源
相似解决方案