You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio 2019中.NET Core项目运行时文本模板找不到TextTemplatingFilePreprocessor怎么办

解决方案

问题原因

Visual Studio 2019的.NET Core/.NET 5+项目默认不会在自定义工具的下拉列表中展示TextTemplatingFilePreprocessor选项,无需额外安装扩展,直接手动填入即可生效。

具体实现步骤

  • 第一步:在项目中新建文本文件,将后缀名修改为.tt(例如ReportTemplate.tt),这就是你的运行时文本模板文件。
  • 第二步:右键该.tt文件,选择「属性」,在「自定义工具」输入栏直接手动输入TextTemplatingFilePreprocessor,按下回车确认,保存文件后Visual Studio会自动生成对应模板的C#包装类,类名和模板文件名保持一致。
  • 第三步:编辑.tt模板文件,定义参数和输出内容,示例模板如下:
<#@ template language="C#" #>
<#@ parameter name="Parameter1" type="System.String" #>
<#@ parameter name="Parameter2" type="System.String" #>
===== 生成的文本内容 =====
参数1取值:<#= Parameter1 #>
参数2取值:<#= Parameter2 #>
  • 第四步:编写调用代码,传入参数生成文本,示例代码如下:
public string SampleMethod(string parameter1, string parameter2)
{
    // 实例化自动生成的模板类
    var template = new ReportTemplate();
    // 构造参数会话字典
    template.Session = new System.Collections.Generic.Dictionary<string, object>
    {
        { "Parameter1", parameter1 },
        { "Parameter2", parameter2 }
    };
    // 初始化模板加载参数
    template.Initialize();
    // 执行转换得到最终文本
    string fileText = template.TransformText();
    return fileText;
}

注意事项

  • 如果手动输入自定义工具后没有生成对应的C#类,打开Visual Studio Installer,在「单个组件」中搜索「文本模板生成」,安装对应组件后重启Visual Studio即可。
  • 你也可以在模板文件中添加<#@ output namespace="你的项目命名空间" #>指令,指定自动生成的模板类的命名空间,方便调用。
  • 如果需要传入复杂类型作为参数,确保该类型对模板生成的类可见,建议定义为公共类型。

内容的提问来源于stack exchange,提问作者Walt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 10:45:02