我正在使用下面的代码将游戏数据序列化/反序列化为 .lst 文件:
public static void SaveData(StoreData data)
{
// Get the path of the save game
string fullpath = Path.Combine("Content", filename);
// Open the file, creating it if necessary
FileStream stream = File.Open(fullpath, FileMode.Create);
try
{
// Convert the object to XML data and put it in the stream
XmlSerializer serializer = new XmlSerializer(typeof(StoreData));
serializer.Serialize(stream, data);
}
finally
{
// Close the file
stream.Close();
}
}
序列化似乎在大多数情况下都能正常工作。这是创建的文件:
<?xml version="1.0"?>
<StoreData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<score>2540</score>
<level>8</level>
<difficulty>true</difficulty>
<sound>true</sound>
<mouseControl>true</mouseControl>
</StoreData>
但有时序列化似乎出错了,在打开文件时,似乎在文件末尾添加了额外的几个字符以创建如下内容:
<?xml version="1.0"?>
<StoreData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<score>2540</score>
<level>8</level>
<difficulty>true</difficulty>
<sound>true</sound>
<mouseControl>true</mouseControl>
</StoreData>a> ---> extra bit added
这会导致游戏在尝试反序列化时崩溃,因为它的格式不正确。如果有人知道为什么会发生这种情况或我做错了什么,请告诉我。
提前致谢。