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:

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)
       line = sr.ReadLine();

And see it on Output console:


But why did they add TitleContainer?

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

Hope you liked this mini-article!

Similar Articles
Araf Global is a software consultancy company founded in 2016 focusing on cutting edge technologies.