Muhammad Abdul-Rahim
Muhammad Abdul-Rahim

Reputation: 2020

File.Create fails on iPhone 5S

I'm working on a Unity game that saves/loads data. I am in the testing phase for this project, and ran into an unusual circumstance in which the game refuses to save in iOS. It works just fine when run on Android, Windows, and OS X. Here is my applicable code:

FileStream file = File.Create(GetSavePath());
bf.Serialize(file, saveFile);
file.Close();

I define GetSavePath() as follows:

private string GetSavePath()
{
    return Path.Combine(Application.persistentDataPath, SAVEPATH);
}

I define SAVEPATH as SaveFile.bin. Please note that the issue is explicitly with File.Create(), as seen in the trace below:

IOException: Sharing violation on path /var/mobile/Containers/Data/Application/4AE45A80-AC36-4A96-9C69-BE01CB753896/Documents/SaveFile.bin
  at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in <filename unknown>:0 
  at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) [0x00000] in <filename unknown>:0 
  at System.IO.File.Create (System.String path, Int32 bufferSize) [0x00000] in <filename unknown>:0 
  at System.IO.File.Create (System.String path) [0x00000] in <filename unknown>:0 
  at SaveManager.Save () [0x00000] in <filename unknown>:0 
  at SaveManager.NewSave () [0x00000] in <filename unknown>:0 
  at GameManager.NewSave () [0x00000] in <filename unknown>:0 
  at TitleManager.NewGame () [0x00000] in <filename unknown>:0 
  at UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) [0x00000] in <filename unknown>:0 

From the above, it should be noted that Invoke is called since the user must click a button to create a new game. The issue with System.IO.File.Create in the trace corresponds to the FileStream file = File.Create(GetSavePath()); above.

Device information:

Unity version: 5.4.1f1

I have yet to test on other iOS devices.

Upvotes: 2

Views: 220

Answers (1)

markten
markten

Reputation: 26

Use File.Open() with the mode FileMode.OpenOrCreate instead of File.Create(). Current speculation is that File.Create() fails to immediately release a lock on the file preventing the returned filestream from accessing the file.

Upvotes: 1

Related Questions