Tag Archives: WP7

Reading Files For Windows Phone 7

I was writing some games using the windows phone 7 tools and I found out that its a pretty cool sdk with .Net framework 4.0. For games you can either do silverlight or XNA. The first decision that you will have to make is to whether go Silverlight or go XNA ? If you plan to have 3D graphics/ animation, extensive control on drawing and coloring, show lot of images or trying to process rapid user input then go with XNA, otherwise silverlight is also pretty powerful if all you have to do is to manipulate windows phone controls and write a little logic to create your app. What I found out is you will need to read data files as there is no support or built in database in the phone. For me its a good thing, I do not want to write database wrappers or start a war with entity framework. File processing and Handling is kind of neat and you can pretty much do everything 90% of the time that you would with a database. I don’t think it is a cool idea to write “Payroll Management System” for a cell phone, I mean common ? what is the computer for ??
So coming from the Web/desktop/laptop world its very simple to read a file in .Net. Here is what you would do normally in ASP.Net or a C# Windows Application.

// Assuming file is in the same directory or your project
StreamReader sr = new StreamReader(“file.txt”);
string str = sr.ReadLine();

Pretty Simple huh !! It is a little tricky with XNA 4.0. Primarily you should have the files in the ContentProject and not your game project. If you look at the Game project references, you will see a reference to the ContentProject. So place the files in the Content Project, then change the file properties. You should change the Build Action property to “NONE” and “Copy to Output directory” to “Copy always”. This would put the files in your executable’s path. XNA provides a TileContainer Class and you can call the static method OpenStream and pass in the path (Content Project).

Stream testpath = TitleContainer.OpenStream(“Content/Test.txt”);
StreamReader reader = new StreamReader(testpath);
string line = reader.ReadLine();

For silverlight since you do not have the content project and the files possibly are included in your project you can do:

Stream testpath = Application.GetResourceStream(new Uri(“Test.txt”, UriKind.Relative)).Stream;
StreamReader reader = new StreamReader(testpath);
string line = reader.ReadLine();

I found this the google way, just putting it out there, it may save some time for someone trying to read files in their windows 7 applications. You can pretty much apply the same logic for StreamWriter to create and write to files.

Happy Coding and Best of luck 🙂

3 Comments

Filed under C#