Android - Straight answer for accessing data via Application.dataPath

I’ve started porting my game to Android and the first thing I tried (like any good programmer) was to build and run. :slight_smile: I noticed that none of the xml files (that set initial values) were loaded. I’ve basically traced it down to what looks like the xml serializer is not finding the files. I don’t know how to know if and where my data files are getting saved when my game deploys.

I did a bunch of searching around and found all kinds of answers (some out of date, some solving other issues). I just want a clear solution for accessing data on android.

My code pre-android is such:

    public static void setDefaultFileLocation() {
        fileLocation = Application.dataPath + "\\Data";
        Debug.Log("fileLocation : " + fileLocation);
    }

    public static void SaveXML<T>(T data, string fileName) { 
        if (string.IsNullOrEmpty(fileLocation))
            setDefaultFileLocation();
         
        string _data = SerializeObject<T>(data); 
         
        StreamWriter writer; 
        FileInfo t = new FileInfo(fileLocation + "\\" + fileName + ".xml"); 
        if (!t.Exists) { 
            writer = t.CreateText(); 
        }
        else { 
            t.Delete();
            writer = t.CreateText(); 
        } 
        writer.Write(_data); 
        writer.Close(); 
        Debug.Log("XML File saved : " + fileName); 
    }
 
    public static T LoadXML<T>(string fileName) { 
        if (string.IsNullOrEmpty(fileLocation))
            setDefaultFileLocation();
         
        if (!File.Exists(fileLocation + "\\" + fileName + ".xml"))
            return default(T);
         
        StreamReader r = File.OpenText(fileLocation + "\\" + fileName + ".xml"); 
        string _info = r.ReadToEnd(); 
        r.Close(); 
        string _data = _info; 
        Debug.Log("XML File loaded : " + fileName); 
         
        return (T)DeserializeObject<T>(_data); 
    }

for reference, i save all of my files under the “Data” folder in the path location.

So, how can I modify this to get android to find, access, and mod the files?

What type of data are you trying to read/write? If you want to safely read/write custom data at run-time, you’re only option is to use Application.persistentDataPath. In my experience, trying to read/write to any other directory on Android has result in security exceptions at run-time.

It should be noted that Application.persistentDataPath is empty on the user’s device by default (and I don’t think that there is a way to override this behavior).