- Home /
"IOException: Sharing violation on path" when Loading Data to Overwrite Save
I am creating a save and load system for my game, and when saving the data onto a file, I wanted to first retrieve the current save file, overwrite some of the class variables, and save it again. However, if I call LoadData() while in SaveData(), I get the "IOException: Sharing violation on path" error. Why is this? There is no error if instead of using LoadData() in the marked line, I just use new PlayerData(), so I know that LoadData() is causing the problem.
public static class SaveSystem
{
static string GetPath()
{
return Path.Combine(Application.persistentDataPath, PlayerData.GetFileName());
}
public static void SaveData()
{
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream(GetPath(), FileMode.Create))
{
formatter.Serialize(stream, PlayerData.GetData());
}
}
public static PlayerData LoadData()
{
if (File.Exists(GetPath()))
{
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream(GetPath(), FileMode.Open))
{
PlayerData data = formatter.Deserialize(stream) as PlayerData;
previousLoad = data;
previousLoadFrame = Time.frameCount;
return data;
}
}
}
}
[System.Serializable]
public class PlayerData
{
// Variables like FileName and player data variables declared
public static PlayerData GetData()
{
PlayerData data = SaveSystem.LoadData(); // *** Problem here ***
data.SetData();
return data;
}
public void SetData()
{
// Variables set here
}
public static string GetFileName()
{
return FileName;
}
}
Have you tried running unity as an ad$$anonymous$$istrator?
Yes, and it didn't change anything.
Answer by Skrimel · Jun 30, 2020 at 12:13 PM
You open file in "create mode" and then trying to access it again. As i understood problem happens when you try to save data, so look at my "callstack" explanation:
> SavingData: line 8
> Creating File with given name without check of the fact that name is already used: line 11 //File stream is getting access to file with name FileName
> Getting player data: line 12
> Loading previous player data : line 40
> Trying to getting access to file, access denied cause it is opened in stream already, that is the problem : line 22
Edit 1: you can solve your problem just in 2 steps: Get player data from previous save, before openning file for write of a new save data And the second one is an advise: check existance of file before it's force creating. You can do it just by changing open mode from "FileMode.Create" to "FileMode.OpenOrCreate"