Friday, May 18, 2012

The trick to reading in text files (or any file) using PlayStation Suite

If you've attempted to use System.IO.File or similar to read a file into your PlayStation Suite project - you may have found it doesn't work very well. It turns out to be quite hard to get the currently executing directory and even then I'm not sure how well that method would work once it's packaged to run on a phone or Vita.

I did a little searching and found this blog post (it's in Japanese) but he uses GetManifestResourceStream from the Assembly class to get access to embedded files.

First off you need to add your file, I'm using a json file called overworld.json it's in my directory structure like so:


Then you need to make the file into an "Embedded Resource"




We are now ready to go!

You can reference the file starting with the the default namespace name. My project is called "Overworld" and that's my default namespace. I reference my overworld file using this string:

"Overworld.data.overworld.json"

There aren't any slashes to denote directories instead you use dots (I don't know why :D I mean generally dots are better because you don't have forward and backward dots but it seems a bit late in the date to be adding some new syntax!)

Here's the code that I've copied from the previous blog then sloppily hacked into an example that works for me. This is in my Initialise function just after the graphics context is created  but I really don't think it matters where you do this.

System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();


var resourceStream = myAssembly.GetManifestResourceStream("Overworld.data.overworld.json");

System.IO.StreamReader IN = new System.IO.StreamReader(
    resourceStream, 
    System.Text.Encoding.GetEncoding("utf-8")); 

var scenario = IN.ReadToEnd();

IN.Close ();

System.Console.WriteLine(scenario);


The most important part is the path to the resource "Overworld.data.overworld.json"

And with that you should be able to load any files you want! I haven't tried this out on actual hardware yet so I'd be very interested to hear how that went if anyone wants to try it.

2 comments:

Tudou said...

GameEngine2D uses similar code to this, but with English comments :)

PS I read your book after starting playing with PS Suite, is there a second one! :)?

PPS your captcha is too hard, it's taken me like 10+ attempts?

balaam said...

Yeh the PlayStation Suite stuff seems pretty nice. I haven't got very far into it though.

No second book yet. I have been toying with the idea but I think I'd go for something more focused like making an adventure game, retro-style-rpg or using the Lua scripting language for games.

The captcha system is controlled by Blogger. I think Google recently had one of their captchas broken, so maybe they beefed it up. I'll see if I can change it.