How to embed a text file in a .NET assembly?

2019-01-01 05:48发布

I would like to embed a text file in an assembly so that I can load the text without having to read it from disk, and so that everything I need is contained within the exe. (So that it's more portable)

Is there a way to do this? I assume something with the resource files?

And if you can, how do you do it and how do you programaticaly load the text into a string?

7条回答
深知你不懂我心
2楼-- · 2019-01-01 06:19

Adding to Pavan's answer, to get the current assembly (in general section):

Assembly _assembly;

GetManifestResourceStream(fileName)(in code, where the read from resource is required):

try
{
    _assembly = Assembly.GetExecutingAssembly();
    _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("*Namespace*.*FileName*.txt"));
}
catch
{
    Console.WritelLine("Error accessing resource!");
}
查看更多
登录 后发表回答