如何在T4模板中更改输出文件?

时间:2019-05-10 06:34:01

标签: c# asp.net asp.net-mvc t4

这是我的代码,工作正常,但是在Enums.tt下创建了.cs文件,文件名为Enums.genic.cs,但是我想在项目中的特定位置创建输出文件,我该如何实现这个?

让我知道有什么方法可以做这些事情。我进行了搜索,但没有找到合适的解决方案。

<#@ template debug="true" hostSpecific="false" #>
<#@ output extension=".generated.cs" #>
<#@ Assembly Name="System.Data" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>

<#
    string tableName = "ContentTypeMaster";
    string columnId = "Id";
    string columnName = "Name";
    string connectionString = "Data Source=192.168.120.71;Initial Catalog=ErisWebsite;Persist Security Info=True;User ID=IM;Password=Intellimedia$#12;MultipleActiveResultSets=True;Connection Timeout=5000";
#>
using System;
using System.CodeDom.Compiler;

namespace ER.ErisCampaign.Enums
{
    /// <summary>
    /// <#= tableName #> auto generated enumeration
    /// </summary>
    public enum <#= tableName #>
    {
<#
    SqlConnection conn = new SqlConnection(connectionString);
    string command = string.Format("select {0}, {1} from {2} order by {0}", columnId, columnName, tableName);
    SqlCommand comm = new SqlCommand(command, conn);

    conn.Open();

    SqlDataReader reader = comm.ExecuteReader();
    bool loop = reader.Read();

    while(loop)
    {
#>      /// <summary>
        /// <#= reader[columnName] #> configuration setting.
        /// </summary>
        <#= Pascalize(reader[columnName]) #> = <#= reader[columnId] #><# loop = reader.Read(); #><#= loop ? ",\r\n" : string.Empty #>
<#
    }
#>  }
}
<#+
    private string Pascalize(object value)
    {
        Regex rx = new Regex(@"(?:[^a-zA-Z0-9]*)(?<first>[a-zA-Z0-9])(?<reminder>[a-zA-Z0-9]*)(?:[^a-zA-Z0-9]*)");
        return rx.Replace(value.ToString(), m => m.Groups["first"].ToString().ToUpper() + m.Groups["reminder"].ToString().ToLower());
    }


#>

1 个答案:

答案 0 :(得分:1)

在T4模板中添加以下方法:

<#
public void SaveFile(string folder, string fileName, string content)
{
    using (FileStream fs = new FileStream(Path.Combine(folder, fileName), FileMode.Create))
    {  
        using (StreamWriter str = new StreamWriter(fs))
        {
        str.WriteLine(content);
        str.Flush();
        }
    }
}
#>

在输出末尾(最后一个<#控制块#>)添加以下行,以防止写入子节点和写入自定义目录/文件:

<#
SaveFile(folder, filename + ".cs", this.GenerationEnvironment.ToString());
this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
#>

This项目包含一些示例。

请注意,它仍将添加一个空的子节点,但文件中未写入任何输出。