Sharing Violation on iOS

For my game, I’m trying to save the player’s progress to a file, and later load from it. I’m doing this by serializing an object that holds the progress. Both saving and loading are working fine from the editor, but when I try an iOS build, I get a sharing violation on the path I’m trying to write to upon saving.

Here’s my code:

string saveFilePath = Path.Combine(Application.persistentDataPath, "progress.txt");

FileStream stream = File.Create(saveFilePath);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, ProgressStore);
stream.Close();

ProgressStore is my object that gets serialized. Through debug messaging, I see that the File.Create is throwing the IOException, but I simply can’t figure out why. I’ve also tried File.Open with various FileMode options, and File.CreateText.

Well, I found that if I trade out the BinaryFormatter for an XmlSerializer, it all just works. Apparently there’s a problem with .NET’s JIT on iOS that was causing it to throw the Sharing Violation.

Ended up changing some stuff around to boot, so the working code looks like this:

using (MemoryStream stream = new MemoryStream()) {
  XmlSerializer progressSerializer = new XmlSerializer(typeof(ProgressObject));
  progressSerializer.Serialize(stream, ProgressStore);
  using (FileStream fileWriter = File.Create(saveFilePath)) {
    byte[] originalData = stream.GetBuffer();
    fileWriter.Write(originalData,0,originalData.Length);
    fileWriter.Close();
  }
}

And yes, this exact same snippet crashes (on iOS only) if you change the XmlSerializer to a BinaryFormatter.

I found this link helpful for explaining how to get the BinaryFormatter to work as an alternative to using the XMLSerializer: