# Saving and Loading File to Application.persistentDataPat not working on Android device

I am trying to save data and load data on the project i am working on, but i cant seem to get it work in an Android device it works fine on Unity when i play it, not sure what i am missing or done wrong here is the following code i use to save and load data.

using System.Collections; using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO;

public class PlayerInfo : MonoBehaviour {

 public static PlayerInfo playerData;
public int gameCoins;

void OnDisable()
{
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Create (Application.persistentDataPath + "playerinfo.dat");

PlayerData data = new PlayerData ();
data.gameCoins = gameCoins;

bf.Serialize (file, data);
file.Close ();
}

void OnEnable()
{
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open (Application.persistentDataPath + "playerinfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize (file);
file.Close ();

gameCoins = data.gameCoins;

}

}
[Serializable]
class PlayerData
{
public int gameCoins;
}


Anyone can give me an idea of what i need to do or look at i will be very much appreciated, and many thanks in advance for taking the time to help.

• Try adding a slash, like Application.persistentDataPath + "/playerinfo.dat" – Chris McFarland Apr 29 '15 at 4:20
• is still not working with the "/" and External setting, :( – Simon Chan Apr 29 '15 at 5:38

1. Like @Chris suggested, try adding a "/" before the file name. You can make sure by printing out the final path with Debug.Log, even in editor, and making sure the path is ok.

2. Make sure you have external write permissions on the device. You can set this up in the android player settings:

• I have done that already, let me try adding a "/" see if it works Thank you for ur replay :) – Simon Chan Apr 29 '15 at 5:33
• did you print out the path in debug log like I suggested? what do you see? – tbkn23 Apr 29 '15 at 12:39
• I find out the problem was not tht the save was not working it was OnDisable thts not working on an android device i now used OnApplicationPause and it works now, thank you very much for your help anyway :D! – Simon Chan Apr 29 '15 at 13:00

Application.persistentData could be different from whether AndroidManifest has WRITE_EXTERNAL_STORAGE permission or not.

I haven't been able to find a solution for this. It seems like opening a FileStream on Android isn't possible. I found this thread which has a work-around. How to use xmlserializer and filestream on android

You have to "download" the file using the WWW class and then you can open a FileStream on the copy.

Honest way is using

Path.Combine(Application.persistentDataPath, "playerinfo.dat")


And not need to change "Write access"