- Home /
Problems when saving and loading with FileStream
Hello everybody. I'm having some File Sharing problems in unity. I need to save and load objects from a few Json files and even though I used StreamReader.Close(), it doesn't seem to work as it should. I'm a bit slow with those backend code stuff, so I really don't know what I'm doing wrong. Does anyone have any suggestion?
using UnityEngine;
using System.Collections;
using System.IO;
using System.Text;
public class SaveLoadManager : MonoBehaviour {
public SaveData saveData;
public static SaveLoadManager manager;
void Awake(){
if (manager == null) {
manager = this;
} else if (manager != null) {
Destroy (gameObject);
}
DontDestroyOnLoad (gameObject);
}
public static string LoadJsonAsResource(string path){
string jsonFilePath = path.Replace (".json", "");
TextAsset loadedJsonfile = Resources.Load<TextAsset> (jsonFilePath);
return loadedJsonfile.text;
}
public string LoadJsonAsExternalResource(string path){
path = Application.persistentDataPath + "/" + path;
if (!File.Exists (path)) {
return null;
}
StreamReader reader = new StreamReader (path);
string response = "";
while (!reader.EndOfStream) {
response += reader.ReadLine();
}
return response;
reader.Close ();
}
public void WriteJsonToExternalResource(string path, string content){
path = Application.persistentDataPath + "/" + path; //caminho do arquivo
FileStream stream = File.Create (path);//cria o arquivo
byte[] contentBytes = new UTF8Encoding (true).GetBytes (content);//converting the string into bytes
stream.Write(contentBytes,0,contentBytes.Length);//escreve os dados no arquivo
stream.Close ();
}
}
Answer by Paul-Sinnett · Nov 08, 2017 at 04:45 PM
Your line reader.Close() is below a return statement. It won't get executed.
Damn, I didn't see that, thank you! Would you have any suggestion on how to stop the Sharing Violation error when I call the WriteJsonToExternalResource? It returns that error every time I need to overwrite the text inside the JSON.
If you have the file left open from an earlier run you may need to close down and restart to clear it.
That was it! Thank you very much, man! I changed the code and it worked like a charm. Thank you again.
Your answer
Follow this Question
Related Questions
About Android can't load json file in Application.persistentDataPath 1 Answer
Android: Trying to reset save data on device when pushing a new build! 1 Answer
How to refer to internal json file on Android? 1 Answer
System.IO in javascript 1 Answer
How to send an Email with the details entered in a json file? 0 Answers