Reading Text Files in XNA for Windows Phone 7 using TitleContainer

So I am working on a simple game that involves creating levels and I want to keep each level in a Text file and read it and build  from that whatever i need to do. So How would you go about doing that? Well if you look around and search you will find people using

   1: Application.GetResourceStream(new Uri("level.txt"));

 

However, when you run that in XNA you will get a “An unhandled exception of type 'System.NullReferenceException' occurred in …”

So now the problem, How can you read your text file. Well, that's where the TitleContainer comes in. You would need to use the TitleContainer.OpenStream(…) and you need to make sure you set the Build Action on your text file as “Content” otherwise you will get “An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Microsoft.Xna.Framework.dll”

Finally, All that is left to do is write the code.

private void LoadLevel()
       {
 
           using(var stream = TitleContainer.OpenStream(@"Levels\level0.txt"))
           {
 
               using (var sr = new StreamReader(stream))
               {
 
                   var line = sr.ReadLine();
                   while (line != null)
                   {
                       Debug.WriteLine(line);
                       line = sr.ReadLine();
                   }
 
               }
           }
       }

Simple enough, Stay tuned to see how you would create levels and swap out the text files.

Tags: , ,
Categories: Windows Phone 7 | WP7 | XNA

Permalink E-mail | Kick it! | DZone it! | del.icio.us Comments (0) Post RSSRSS comment feed