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.
Post a Comment