Read a file compile-time in C#

前端 未结 6 1309
攒了一身酷
攒了一身酷 2021-01-05 13:37

I am writing some unit tests in which I need a fake xml file. I can create that file and require it to be deployed with the unit tests, but experience shows that at my offic

6条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 14:29

    You can do this with a T4 template. What you need is 3 things

    1. Create your template file, which will generate your .cs code
    2. Include your text file (or *.sql file) in the same project as your template file
    3. Configure your template to re-create your t4 template on every build

    Something like this for your template.tt file

    <#@ template debug="true" hostSpecific="true" #>
    <#@ output extension=".cs" #>
    <#@ Assembly Name="System.Core" #>
    <#@ Assembly Name="System.Windows.Forms" #>
    <#@ import namespace="System" #>
    <#@ import namespace="System.IO" #>
    <#
       string TextFromFile = File.ReadAllText(Host.ResolvePath("my_file_next_to_my_template.txt"));
    #>
    // This is the output code from your template
    namespace MyNameSpace
    {
        class MyGeneratedClass
        {
            static void main (string[] args)
            {
                System.Console.WriteLine("<#= TextFromFile #>");
            }
        }
    }
    

    If you don't want to configure your template to be re-created on the build then just opening it and saving it will do the trick.

提交回复
热议问题