I have two functions which both save and load small XML files. They work great, but whenever I use the load function when there’s no XML file present in the specified location, it throws an error, which ends the function early and leaves the filestream unclosed, which leads to more errors.
At first I thought that CanDeserialize() was used to detect if something was there, since it returns a bool and has “can” in its name, but I’m not using it right. Here’s a look at my code:
XmlSerializer serializer = new XmlSerializer(typeof(T));
//(Where are we putting this file, how are we opening it)
FileStream stream = new FileStream(Application.dataPath + "cubeData.xml", FileMode.Open);
//Double checks to see if the xml reader CAN read anything there, if not, return null
if (!serializer.CanDeserialize(XmlReader.Create(new FileStream(Application.dataPath + "cubeData.xml", FileMode.Open)))) return null;
When I run this when there’s no XML file to load, it returns errors and my code is ended early.
Here’s the full load function:
public T LoadGame <T> () where T : class
{
//First two lines of code are shamelessly copied from savegame(), except we CHANGE FROM FILEMODE.CREATE to FILEMODE.OPEN
Debug.Log("attempting load");
XmlSerializer serializer = new XmlSerializer(typeof(T));
//(Where are we putting this file, how are we opening it)
FileStream stream = new FileStream(Application.dataPath + "cubeData.xml", FileMode.Open);
//Double checks to see if the xml reader CAN read anything there, if not, return null
if (!serializer.CanDeserialize(XmlReader.Create(new FileStream(Application.dataPath + "cubeData.xml", FileMode.Open)))) return null;
//You need to include the stream in the deserialize function
T theClass = serializer.Deserialize(stream) as T;
stream.Close();
Debug.Log("loading successful");
return theClass;
}
(When I use this code, I never save DIFFERENT classes using this function to cubeData.xml, I just included the variable T in the function to get more comfortable with it in my functions. Whenever I use the Save and Load function, I always use the same class which is changed to XML format)