- Home /
Sharing Violation On Path
So I've redone my save/load script, but I am encountering a Sharing Violation On Path error.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class SaveAndLoad
{
public static BinaryFormatter binaryFormatter = new BinaryFormatter();
public static void Save(string saveString, object obj, string saveName)
{
string fileType = ".dat";
string saveGameName = saveName + fileType;
//Create directory if missing
if(!Directory.Exists("saves/"))
{
Directory.CreateDirectory("saves/");
Debug.Log("Save directory missing, creating new save directory. 'saves/'");
}
else
{
Debug.Log("Save directory exists.");
}
//Check if file exists, if not, create file. If the directory does not exist, create one and try again.
if(File.Exists("saves/" + saveGameName))
{
Debug.Log("Save data exists.");
}
else
{
File.Create("saves/" + saveGameName);
Debug.Log("Save data missing, creating new empty save data.");
}
//Save game data to file.
FileStream fileStream = File.Open("saves/" + saveGameName, FileMode.Open);
StreamWriter writer = new StreamWriter("saves/" + saveGameName);
SaveData data = new SaveData();
data.playerStatData.playerAttributes = data.playerStatData.playerAttributes;
data.playerStatData.playerSkills = data.playerStatData.playerSkills;
writer.Write(data);
//binaryFormatter.Serialize(saveGameName, data.GetData());
fileStream.Close();
}
public static object Load(string saveString, object obj, string saveName)
{
string saveGameName = saveName + ".txt";
string temp = File.ReadAllText(saveGameName);
if(temp == string.Empty)
{
return null;
}
MemoryStream memStream = new MemoryStream(System.Convert.FromBase64String(temp));
return binaryFormatter.Deserialize(memStream);
}
[System.Serializable]
class SaveData
{
public RPGSystemPlayerStats playerStatData;
public void GetData ()
{
playerStatData.ToString();
}
}
}
In SaveAndLoad you should probably use the FileStream you open for the StreamWriter or not make a FileStream at all. It seems likely that opening a StreamWriter using the same string as the FileStream is causing your program to access the same file twice which then causes the file sharing violation.
Answer by Dagra · Mar 18, 2015 at 05:54 AM
I actually learned to do this from digging through the code in this asset so giving credit.
https://www.assetstore.unity3d.com/en/#!/content/20891
I learned a lot from this and its worth getting to dig through the code.
the simplified version of it to get you started is below where load_path and fileContens are all strings.
using(StreamReader reader = new StreamReader(load_path))
{
fileContents = reader.ReadToEnd().ToString();
}
if you are having trouble getting the proper file path (like I did) use the file picker and debug.log to see your path. load_path = EditorUtility.OpenFilePanel
from there I could parse the string out. hope that helps.