1

Suppose I have a text file (such as a SQL query) stored in my Visual Studio project. Is there any way I can save the file's contents to a variable at compile time? I just want to have some text in its own file, instead of having a really long quoted string in my source code; but I don't want the hassle of having to deploy (or keep track of) the file.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
nomen
  • 3,626
  • 2
  • 23
  • 40
  • 1
    Really at compile time and not run-time? – pay Jun 03 '16 at 19:51
  • Compile-time would mean you want the contents of that file compiled into your source code. Run-time would be: ok, I need to run this query, read it out of the file and run it. Which is it you're after? – Cᴏʀʏ Jun 03 '16 at 19:52
  • 2
    Embed as a resource and use it when needed... – AlG Jun 03 '16 at 19:53
  • @Cᴏʀʏ but you could still just read the file at run-time and just save the query in memory for later and not necessarily execute it right away... that's why I asked, a little confused. – pay Jun 03 '16 at 19:54
  • How about just putting your text/query in a resource file and access it from there? – Cᴏʀʏ Jun 03 '16 at 19:57

1 Answers1

0

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.

Frank Bryce
  • 8,076
  • 4
  • 38
  • 56