2

I'm looking for a way to read content of a file at compile time and replace value of a const with it:

public class MyClass {
  
 [LoadFromFile("/myFile.txt")]
 public const string MyConst = "";

}

This will read content of file myFile.txt (probably using File.ReadAllText or anything else) in directory relative to the working directory, content of this file could be for example:

Hello world

And in compiled assembly MyClass.MyConst would return Hello world.

Research led me to https://github.com/Fody/Fody and to "assembly weaving". How would you approach this problem? Are there any other ready to use solutions for this? I'm using .NET 5.

Matěj Štágl
  • 870
  • 1
  • 9
  • 27
  • A root relative file reference would seem very problematic. – NetMage Jan 22 '21 at 21:24
  • It might be helpful to explain why you want to load a "const" from a config file in the first place. Maybe the heart of the problem is that you should be using `IConfiguration` and dependency injection instead of getting a global constant. – Kevin Krumwiede Feb 04 '21 at 01:20

2 Answers2

5

I would use an embedded resource, and then make MyConst a

public static readonly string MyConst = ReadResource("MyFile.txt")

See How to read embedded resource text file (note that the ReadResource in the response can be made static).

I think that wasting time including Fody (and studying it, and following it through versions) for such a thing is foolish.

xanatos
  • 109,618
  • 12
  • 197
  • 280
0

not a const, but using using https://github.com/Fody/Resourcer you could embed myFile.txt as a resource then do

var myFileContents = Resource.AsString("myFile.txt");
Simon
  • 33,714
  • 21
  • 133
  • 202