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.
            Asked
            
        
        
            Active
            
        
            Viewed 1,287 times
        
    1
            
            
        - 
                    1Really 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
- 
                    2Embed 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 Answers
0
            
            
        You can do this with a T4 template. What you need is 3 things
- Create your template file, which will generate your .cs code
- Include your text file (or *.sql file) in the same project as your template file
- 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
 
    