How to use a resx resource file in a T4 template

后端 未结 4 1088
不思量自难忘°
不思量自难忘° 2021-01-03 11:24

I cant figure out how to include the resource file (.resx) in the (.tt) T4 template.

I tried so far... Importing the namespace

<#@ import names         


        
4条回答
  •  不知归路
    2021-01-03 12:22

    Nico's solution requires your solution to build.

    There is another way, without needing to compile your solution by reading the raw resx file.

        var fileName = "CustomResource.resx";
        var filePath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "WindowsFormsApplication1", fileName);
        var reader = new ResXResourceReader(filePath);
        var values = reader.Cast().ToDictionary(x => x.Key, y => y.Value);
    
        // this is how you would acces the resources
        var value = values["entry"];
    

    You should be aware that this method lacks design time checking if the resource does not exist and you don't get localized values because you are just reading a file. Both are often not mandatory withing T4 templates

    Here is a working snipped that creates an enum from a resource file.

    Just make sure you use set the right values for fileName and filePath

    <#@ template debug="false" hostspecific="true" language="C#" #>
    <#@ output extension=".cs" #>
    <#@ assembly name="System.Windows.Forms" #>
    
    <#@ import namespace="System.Resources" #>
    <#@ import namespace="System.Collections" #>
    <#@ import namespace="System.IO" #>
    <#@ import namespace="System.ComponentModel.Design" #>
    
    <#
    
        var nameSpace = "WindowsFormsApplication1";
        var enumName = "CustomEnum";
    
        var fileName = "CustomResource.resx";
        var filePath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "WindowsFormsApplication10", fileName);
    
        using (var reader = new ResXResourceReader(filePath))
        {
    
            reader.UseResXDataNodes = true;
    #>
    
    namespace <#=nameSpace#>
    {
    
        public enum <#=enumName#>
        {
    
            Undefined,
    
            <#  foreach(DictionaryEntry entry in reader) { 
    
                var name = entry.Key;
                var node = (ResXDataNode)entry.Value;
                var value = node.GetValue((ITypeResolutionService) null);
                var comment = node.Comment;
                var summary = value;
                if (!String.IsNullOrEmpty(comment)) summary += " - " + comment;
            #>
    
            /// 
            /// <#= summary #>
            /// 
            <#= name #>,
    
            <# } #>
    
        }
    
    }
    
    
    <#
        }
    #>
    

提交回复
热议问题