0

I am making a console program in VS2010. The structure of as layed out in the solution explorer is Project file, Properties folder, References, and Program.cs.

I want to make use of a text file for reading/writing. What is the correct way of adding this file to the project? If I just do StreamWriter sw = new StreamWriter("maze.txt") then it'll create the file in the output folders (bin/debug or bin/release). But it won't show up in the solution explorer.

Now if I right-click on the solution explorer and Add New Item, I can create a text file in the root project folder (same level as Program.cs). This will show up in the solution explorer.

Is there a way for me to access this newly created file? Other than doing something like StreamWriter sw = new StreamWriter("../../maze.txt") by specifying the path to be two parents up?

How am I supposed to manage external files in a Visual Studio console applicatoin? In a WinForms application, there's a resources folder where I can add these things and a Resources.resx file to manage it. I can access it with Properties.Resources.someres.

Jonas
  • 589
  • 2
  • 4
  • 12

3 Answers3

5

If you want to create a file at design time and have it included in your bin folder then add the text file, go to properties, and select "copy always" or "copy if newer" for the copy property.

Note that this will copy the file from the project to the bin folder, but changes in the bin folder when debugging won't be copied up into the project itself. I doubt you want the program to interact with the version of the file in the project itself. If you do something like that then anytime you run the program outside of VS (i.e. when you copy it to the machine of an actual user) it won't work.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • Well I know I can do copy the file to the bin folder but I'm just wondering if I'm supposed to access the text file like `StreamWriter("../../maze.txt")` or if there was a more streamlined way like `StreamWriter(Properties.Resources.maze)` where the file is really part of the project. – Jonas Apr 27 '12 at 14:14
  • No, you shouldn't be accessing the file that is actually a part of the project while the program is running at all. The program itself should only be modifying the copy of the file that's in the bin/debug folder. – Servy Apr 27 '12 at 14:38
1

As for your resources question, you can still use resources. Just right-click and "Add" -> "New Item" (aka keyboard shortcut Ctrl+Shift+A) and choose "Resources File". You could also set the text file to be an Embedded Resource. MSDN has a lot of information on using resources on their Managing Application Resources page.

scottheckel
  • 9,106
  • 1
  • 35
  • 47
1

You can still embed resources to a console application. I've used this technique in quick apps so we don't need a installer or deploy dependencies such as these type of files. This question discusses a similar topic.

Community
  • 1
  • 1
Ulises
  • 13,229
  • 5
  • 34
  • 50