简体   繁体   中英

Using text files in Visual Studio Project

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 .

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 (ie when you copy it to the machine of an actual user) it won't work.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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