Unity doesn't detect txt file after build

StreamReader inp_stm = new StreamReader(Application.dataPath + “/allNames.txt”);
I have this line of code in my project, it reads the provided text file in the editor runtime.
However, when I build it will not find the file, when it is placed next to the .exe.
How exactly can I fix this ?

Try adding your file to the Resources folder.


Then you can use the Resources.Load() Command to get the text file. I think the issue is that when you build, everything not referenced in the code is excluded. And since the text file isn’t referenced (Unity doesn’t realise the path string is a reference) its not added to the final build. But putting it in the resource folder will force it to be added.

Have you read the documentation of Application.dataPath?
You haven’t mentioned your target platform, however since you said “exe” we can assume you build for windows standalone. As you can read in the documentation dataPath will return the path to the “_Data” folder of your build.

You also can easily debug this issue by logging your used absolute path / filename using Debug.Log. To find the log file for your build, see LogFiles

Your random files are not copied into the build. If you want your random files to be copied to the build, place them in the StreamingAssets special folder, or do it yourself in some post-build script
Then you can use Application.streamingAssetsPath to access them