- Home /
 
Writing binary files on Android
I have this code snippet to save/load class objects into/from binary files. It works perfectly on Windows:
 public static void SaveFile(string filename, System.Object obj)
 {
     try
     {
         filename = Application.dataPath + @"\Resources\SaveLoad\" + filename;
         Stream fileStream = File.Open(filename, FileMode.Create, FileAccess.Write);
         BinaryFormatter formatter = new BinaryFormatter();
         formatter.Serialize(fileStream, obj);
         fileStream.Close();
     } 
     catch (Exception e)
     {
         Debug.LogWarning("Save.SaveFile(): Failed to serialize object to a file " + filename + " (Reason: " + e.Message + ")");
     }
 }
 
 public static System.Object LoadFile(string filename)
 {
     try
     {
         filename = Application.dataPath + @"\Resources\SaveLoad\" + filename;
         Stream fileStream = File.Open(filename, FileMode.Open, FileAccess.Read);
         BinaryFormatter formatter = new BinaryFormatter();
         System.Object obj = formatter.Deserialize(fileStream);
         fileStream.Close();
         return obj;
     } 
     catch (Exception e)
     {
         Debug.LogWarning("SaveLoad.LoadFile(): Failed to deserialize a file " + filename + " (Reason: " + e.Message + ")");
         return null;
     }       
 }
 
               What modifications have I to do to make it save/load properly on Android? And hopefully on all other mobile platforms as well.
Answer by Bunny83 · May 21, 2016 at 01:56 AM
Don't use "Application.dataPath" but use Application.persistentDataPath. This will return a path that is ment to store and load data on any build platform except web platforms where FileIO isn't available.
Your answer
 
             Follow this Question
Related Questions
[C#] Saving settings to a local file and reading from it at runtime 1 Answer
SerializationException: Type UnityEngine.UI.Button is not marked as Serializable. Solution 1 Answer
Delete a serialized binary save file 2 Answers
Change location of binary file created when saving 1 Answer
from bool array to binary file? 1 Answer