- Home /
IOException: Sharing violation on path
For some reason I keep getting the error IOException: Sharing violation on path when trying to run SaveScores. This code is meant to load the list of all the scores the player has gotten, adds a score to it, and then saves that. Do any of you know what is wrong with it?
public void SaveScores(float score){
List<float> playerScores = LoadScores();
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/highscores.save");
Scores scoreClass = new Scores();
playerScores.Add(score);
scoreClass.scores = playerScores;
bf.Serialize(file, scoreClass);
file.Close();
}
public List<float> LoadScores(){
List<float> scores = new List<float>();
if (File.Exists(Application.persistentDataPath + "/highscores.save"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/Highscores.save", FileMode.Open);
Scores scoreClass = (Scores)bf.Deserialize(file);
scores = scoreClass.scores;
file.Close();
}
return scores;
}
I know that you ask for "SaveScores".. but do you see that in "LoadScores" the path in the if statement and the path in FileStream are different? One with "high score" in lowercase and one with the "H" in uppercase.. just for the future :D
Is it possible that you call this code repeatedly like in the Update method? If yes, the problem is that the Stream does not have time to close the stream that is already requested to overwrite it .. for this it throws the exception.
Answer by xxmariofer · Jul 01, 2021 at 07:12 AM
could you try adding usings?
using(BinaryFormatter bf = new BinaryFormatter())
{
using(FileStream file = File.Create(Application.persistentDataPath + "/highscores.save"))
{
just in case the garbage collector is not deleting the objects
Your answer
Follow this Question
Related Questions
Serialized Data Not Saving on Android Build 0 Answers
Serialization Exception Error When Trying to Load 2 Answers
I am getting a serialization exception error when trying to save and load in Unity? 2 Answers
Binary Serialization (In Editor) - Path Access denied / File not found 0 Answers
Saving Game Confussion 1 Answer