简体   繁体   English

从构建中读取txt文件,而无需编写它们

[英]Read txt files from build without writing them

I want to make a console application which tests a .txt file to be included with the application. 我想制作一个控制台应用程序,用于测试要包含在该应用程序中的.txt文件。 However, File.ReadAllLines(string) seems to have only the string-filepath constructor and not one taking the file itself, which could be accessed by mytextfile = myProject.Properties.Resources.mytextfile.txt; 但是,File.ReadAllLines(string)似乎仅具有string-filepath构造函数,而没有一个本身获取文件的构造函数,可以通过mytextfile = myProject.Properties.Resources.mytextfile.txt;访问该文件。

so do I have to write the file from the build somewhere, call reflection on it to find out its full path and only then be able to use ReadAllLines() to convert it into a string-array? 所以我是否必须从某个地方的构建中写入文件,对其进行调用反射以找出其完整路径,然后才能够使用ReadAllLines()将其转换为字符串数组? is there no easier way to do this? 有没有更简单的方法可以做到这一点?

You can open the embedded resource as a stream like this: 您可以像这样的流打开嵌入式资源:

Assembly assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream("Namespace.mytextfile.txt");

and then get the text from the stream like this: 然后像这样从流中获取文本:

var reader = new StreamReader(stream);
var text = reader.ReadToEnd();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM