Read file compilation time in C #

I am writing some unit tests in which I need a fake XML file. I can create this file and require it to be deployed with unit tests, but experience shows that I have a lot of headache in my office. Therefore, I decided that the file would be created by UT.

StreamWriter sw = new StreamWriter(testFileName); sw.Write(contents); sw.Close(); 

Now the problem is the content bar. This is almost a long xml, something like this:

 string contents = @"<?xml version="1.0" encoding="windows-1251"?> <blah> ~100 lines here </blah> "; 

I do not want this to be in the same file as the rest of the code. I want the string to be generated at compile time from a file.

In C ++, I would do this

 string contents = " #include "test.xml" "; 

Is this possible somehow in C #?

+6
source share
6 answers

Why don't you include it in the resource?

+9
source

Use resources (resx file) and add xml file. Then you can access using MyNs.MyResources.MyXmlFile.

+1
source

I usually add such test files directly to the C # unit test project and set them as โ€œContentโ€ and โ€œCopy if newerโ€ to copy to the bin directory at compile time.

0
source

If the content is static, why can't you pass it to the original control? Add it to your project, and then it will always be exactly where you expect it.

0
source

You can follow the path of the resource file, but depending on how many resources / how large they are (and the XML can be large), you may run into compilation problems (I did).

Since then, I have moved from resources to singles. Reading a text file using File.ReadAllText is pretty simple and still compatible with IntelliSense.

0
source

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

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 do not want your template to be recreated on the assembly, just open it and save it to do the trick.

0
source

Source: https://habr.com/ru/post/892246/


All Articles