We are making strong progress on an XNA Community Game title that we are working on and I have just spend a good 30 minutes trying to figure this out. Hence, I’m writing this as a future reference for myself and in the hope that it might help any coders out there trying to achieve the same thing.

The Problem

Our game is relatively simple and we would like to define the stages that the player progresses through in a plain text file. While it’s a very simple task to read a text file in C#, I initially had problems assuming that loading a new StreamReader on the the Xbox like so StreamReader(“LevelIndex.txt”); would load up a text file in the same directory as my executable. Not the case - it turns out that, as the Xbox doesn’t really follow a directory structure like a PC, this doesn’t work.

The Solution

The solution is also relatively simple, but not east to find - as it’s one of those things that you either know how to do or not. There are 2 important things to note before jumping directly into a code listing.

1. StorageContainer.TitleLocation: In order to construct the file path that you will be feeding into a StreamReader, you must prefix your path with this property. To load up the file ‘LevelIndex.txt’, which resides in the root directory of your solution, you must construct the path as follows; String fullPath = StorageContainer.TitleLocation + “LevelIndex.txt”;

2. Build Action (None), Copy to Output Directory (Copy if Newer): As your text file is not going to be processed by the Content Processor, you need to tell Visual Studio what should be done with your text file. For my project, I dragged and dropped the text file into my Solution (but NOT in the Content directory). The text file sits alongside your .cs files (although, could reside in a folder). Then, you must change the properties of the text so that Build Action is set to ‘None’ and Copy to Output Directory is set to ‘Copy if Newer’. This ensures that Visual Studio doesn’t try to compile the file as code or include it in your Content repository. It will simply copy the text file to the TitleLocation of your game - just what you want so that you can read it from within your title.

Code Listing

The following code listing shows how we have implemented a simple text file reader for an Xbox XNA Project;

function String[] readStageTitles( String filePath ) {
  ArrayList stageTitles = new ArrayList();
  String[] returnData = null;

  // Both Windows and Xbox - Ensures we are looking in the game's folder.
  String StageIndexPath = StorageContainer.TitleLocation + "\\" + file;

    StreamReader streamReader = new StreamReader(StageIndexPath);
    String line;

    while ((line = streamReader.ReadLine()) != null)
      String[] data = line.Split(';');

      if ( data.Length == 2 ) {

  catch( Exception ex )
    // Do things here incase it can't read the file

  returnData = (String[])stageTitles.ToArray( typeof(String) );
  return returnData;

Hope this helps someone out there.