XNA 3.0 – Reading Text Files on the Xbox

John WordsworthProgramming22 Comments

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.

John WordsworthXNA 3.0 – Reading Text Files on the Xbox

22 Comments on “XNA 3.0 – Reading Text Files on the Xbox”

  1. mauricio

    Thank you man, I really appreciate this peace of help since you explained it in a very comprehensive way.

  2. fade3e@live.com

    i am having trouble reproducing this on the zune it keeps hanging at
    StreamReader streamReader = new StreamReader(CustomerDir);
    the error is
    An unhandled exception of type ‘System.IO.IOException’ occurred in mscorlib.dll

    Additional information: IOException

    i have checked and nothing is mispelled in file name, extention is there, it just wont work for me
    please reply or email me woth help

  3. drozzy

    Why can’t I put it into Content folder? I put it in there and selected “Copy if newer” and can load it fine with “Game.Content.RootDirectory” + “levels/level1.txt” path?

    1. John Wordsworth

      Many thanks Wazoo – I’ll update this article to point to the MSDN entry when I’ve ironed out the last few bugs from the blog design! I’m hoping to start on some articles based on things that I learnt from Ikaroids soon – so hopefully for XNA content coming soon!

  4. Anya

    Thanks so much for this. I was battling with it for a while last night and wonderimg why it couldn’t find the file in StorageContainer.TitleLocation. All I’d missed was the “copy if newer” option.

  5. dota 2 videos

    Thanks for every other fantastic post. Where else may
    just anybody get that type of information in such an ideal way of writing?
    I have a presentation subsequent week, and I’m on the look
    for such info.

  6. read this

    Hey there! This is my first visit to your blog! We are a team
    of volunteers and starting a new initiative in a community
    in the same niche. Your blog provided us valuable information to work on. You have done a extraordinary job!

    1. Eve

      Mauricio.R disse:“Seu comentário maldoso sobre a Em;8,er…&#r221bAlmeidaaSua arrogância é bem tipica da Embraer.Se acha a ultima bolacha do pacote, não adimita qq critica e menos ainda concorrência.Lhes falta humildade e argumentação p/ rebater as criticas recebidas.Sou um piloto de caça frustado, a FAB foi justamente operar Mirage e ainda por cima uso um óculos fundo de garrafa daqueles.Mas curto material bélico como hobby, acompanho mercado, tecnologias e tendências e estou bem longe de ser o dono da verdade.Ah, tb sou operador de console maiframe na IBM.

  7. Jeffrey

    Were you aware that the city of Boston is the metropolis capital of Massachusetts and it also
    sits within the larger region of Greater Boston. If you have a property in a project like this, then renting it out will be easier and the rent amount will
    also be more. For more details on Bangalore Real Estate Prices, log on to magicbricks.

  8. http://www.libraconcept.com/

    lelllllllllllllllllllllllllllllllllllllllllllllllllla scrive:cara io e te pensiamo sempre le stesse cose…. non ho più parole…. justin ma come ci diventi????!!!!un po va bene ma poi BASTA!!!!!!!!!!!!!!!!!!!!!!!!!!! noi beliber ti amiamo per la tua dolcezza, simpatia,non credo ke è merito di DIO se sei arrivato al successo ma ..tutto grazie a noi1!!!!quindi ….Basta tatoo!!!!!!!!!!!!!altrimenti ….

  9. http://www./

    Puuhelmistä vielä.Tälläinen viesti tuli eilen spostiin.”Kiitos 15.10.08 eShopille tekemästäsi tilauksesta. Postitamme tilauksesi tänäänkirjeenä ja Suomen Posti kantaa sen Sinulle suoraan kotiin muutaman päivän sisällä.”Tilasin helmet jo insertin aikana, mutta silti päädyin jonotuslistalle.

  10. http://www./

    Tinha uma empresa aberta como ME dei entrada no encerramento da empresa em 07/2012 na junta comercial, na receita federal, no estado e na prefeitura. Em todos os órgãos a baixa já se concretizou apenas na receita federal a empresa continua como ativa. Agora estou precisando abrir um Mei e não consigo pq no meu cadastro consta que já tenho empresa, o que faço???

  11. http://www./

    Indeed. People’s health should not ever become a “business matter”. It should always be about what is best for people. Let’s get down to brass tacks here and forget about politics and party lines, and (insertnamehere)care — we need to fight for people’s lives and our children’s well-being. Since when has healthcare become a symbol for capitalism? No! Healthcare is about doing unto others.Simple.

Leave a Reply

Your email address will not be published. Required fields are marked *