如何读取现有的文本文件,而无需定义路径文本文件、路径、定义

2023-09-04 09:46:35 作者:繁花落幕丶殇满地

大多数例子说明了如何读取准确位置的文本文件(FEC:\用户\用户\文档\ test1.txt的)。但是,如何读取文本文件,而无需编写完整的路径,所以我的code当复制到其他计算机上是可行的。与Visual Studio我加了2文本文件的项目(控制台项目),不知道阅读这些文件的最好方法。希望我描述了我的问题清清楚楚。也许我需要(直接喜欢同一文件夹中的.exe文件)differentely添加这些txt文件?

Most of the examples shows how to read text file from exact location (f.e. "C:\Users\Owner\Documents\test1.txt"). But, how to read text files without writing full path, so my code would work when copied to other computers. With visual studio I added 2 text files to project (console project) and don't know best way to read those files. Hope I described my problem clearly. Maybe I needed to add those txt files differentely (like directly to same folder as .exe file)?

推荐答案

您可以使用Directory.GetCurrentDirectory:

var path = Path.Combine(Directory.GetCurrentDirectory(), "\\fileName.txt");

这将寻找 FILENAME.TXT 在应用程序的当前目录下的文件。

Which will look for the file fileName.txt in the current directory of the application.