How to use TitleContainer in XNA


In this mini-article I will be talking about how to use TitleContainer

Generally TitleContainer is a new feature in XNA 4.0 and its being used to read external files such as xml,txt and other readable contents.

TitleContainer has one method named "OpenStream" which returns Stream but you can read it through a StreamReader and it takes a string parameter.

Lets make an example and see how its being used:

Create a new project and then create a folder(Levels) and inside this folder create a new xml file(Level1.xml) that looks like:

1.gif
  
Then in our code(anywhere you'd like to use);

using (var levelfile = TitleContainer.OpenStream(@"Levels\level1.xml"))
{
  using (var sr = new StreamReader(levelfile))
  {
    var line = sr.ReadLine();
    while (line != null)
    {
       Debug.WriteLine(line);
       line = sr.ReadLine();
    }
  }
}

And see it on Output console:

2.gif

But why did they add TitleContainer?

Simple.To solve "System.NullReferenceException" exception while using streams.

Hope you liked this mini-article!


Similar Articles