1

So, I have been working on a project, an educational software, something like that. I used a lot of text, images, videos and so on. It's for a contest. My biggest concern came when I found out that if I try to open the app on another PC,it will crah because of the texts that are imported from .txt files located on my PC.

After searching for a little, I found out, if a place the .txt file inside my project, it would solve the problem and I could read it very simple with the second command provided. But it was a mess. I had over 50+ .txt files. Imagine what mess it would have been if I had put all my .txt files inside the project. By putting a .txt file inside the project I mean right-click project name->Add->Existing file. I created a folder inside the project and put all the .txt files inside in it, but the second command it won't work anymore.


Is there a way to acces all the .txt files from a folder within the project, or a way to make the app portbable, no matter what is the .txt file paths. ?

Note: This is a text project, where I used only one .txt file for a test, but the same problems I encountered.


enter image description here


First command I used:

StreamReader read = new StreamReader(@"DC.txt");

And the Second command I used:

StreamReader read = new StreamReader(@"C:\Users\Cristi\Desktop\DC.txt");

ChJ16
  • 51
  • 1
  • 9
  • You need to make "copy always" your files .txt inside the project because if you release the project, the text file will be not inside. You can use a relative path if you copy always – thelittlewozniak Feb 04 '19 at 20:49
  • Once you have the path to the EXE (see the duplicate), use `Path.Combine` to get from there to the `txt` file you are trying to open. – mjwills Feb 04 '19 at 20:52
  • I changed it to "copy always". But it still crashes. It is because the command I used ? StreamReader read = new StreamReader("DC.txt"); – ChJ16 Feb 04 '19 at 21:00
  • Please **do not** use `texts\DC.txt` as suggested. This will work, temporarily. But if, for some reason, the `CurrentDirectory` of your process changes your work will stop working. Please use the technique I suggested to protect against that. – mjwills Feb 04 '19 at 21:10

1 Answers1

1

When you click on DC.txt, you should see in the file properties, "Copy to Output Directory". Change that to "Copy Always", and DC.txt will always be copied into your build directory when it's being built. (This way you wont need to use an absolute path anymore)

Blue
  • 22,608
  • 7
  • 62
  • 92