How to put files in sensible places


I’ve been in the lab marking student work all day. I’ve watched around 25 or so demonstrations of software. Great fun. You might find it surprising, but I actually like this part of the job. Very hard work, but worth it just to see what students have done with the problem that we set. Every now and then I tell a student about something and they say “You should blog that”. And so here goes.

One of the things you often need to do is store a file from your program. You want to put the file somewhere sensible, for example in the user’s documents folder. If you want to find out where this is you can use an environment variable:

string docPath = 
System.Environment.SpecialFolder.MyDocuments); string fileName = docPath + @"\MyFile.txt";

The code above creates a string variable called docPath which refers to the documents folder for that user. It then creates a filename (remembering to put the backslash path separator in and use the string notation that stops it from turning into a control character) which can be used to create a file called MyFile.txt in that folder.

If you use Intellisense you can find lots of other special folders, including the ones for music and photos.