我正在寻找一种在编译时读取文件内容并用它替换 const 值的方法:
public class MyClass {
[LoadFromFile("/myFile.txt")]
public const string MyConst = "";
}
这将读取相对于工作目录的目录中文件 myFile.txt
的内容(可能使用 File.ReadAllText
或其他任何东西),该文件的内容可以是例如:
Hello world
并且在编译后的程序集中 MyClass.MyConst
将返回 Hello world
。
研究使我找到了 https://github.com/Fody/Fody 和“组装编织”。你会如何处理这个问题?是否有其他现成的解决方案?我使用的是 .NET 5。
答案 0 :(得分:4)
我会使用嵌入的资源,然后使 MyConst
成为
public static readonly string MyConst = ReadResource("MyFile.txt")
请参阅 How to read embedded resource text file(注意,响应中的 ReadResource
可以设为 static
)。
我认为为这样的事情浪费时间包括 Fody(并研究它,并通过版本跟踪它)是愚蠢的。
答案 1 :(得分:0)
不是常量,但使用 https://github.com/Fody/Resourcer 您可以将 myFile.txt
作为资源嵌入然后执行
var myFileContents = Resource.AsString("myFile.txt");