XNA:保存数据到文件和从文件读取数据
基于最新的XNA Game Studio 4.0的环境下,因为XNA Game Studio 4.0以前的版本有些方法有变动。
前提:已经有一个正确的StorageDevice和定义好要保存的数据。
public struct SaveGameData
{
public string PlayerName;
public Vector2 AvatarPosition;
public int Level;
public int Score;
}
一.To serialize data to a save game file
1.Create a StorageContainer to access the specified device.
IAsyncResult result = device.BeginOpenContainer("StorageDemo", null, null);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
StorageContainer container = device.EndOpenContainer(result);
// Close the wait handle.
result.AsyncWaitHandle.Close();
2.Call FileExists to determine if an earlier save game file exists, and if it does, call DeleteFile to delete it.
// Check to see whether the save exists.
if (container.FileExists(filename))
// Delete it so that we can create one fresh.
container.DeleteFile(filename);
3.Create a Stream object on the file by using the CreateFile method.
Stream stream = container.CreateFile(filename);
4.Create an XmlSerializer object, passing the type of the structure that defines your save game data.
XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
5.Call Serialize, and then pass the Stream and the data to serialize.
The XmlSerializer converts data in the structure to XML, and uses the Stream to write the data into the file.
6.Close the Stream.
stream.Close();
7.Dispose the StorageContainer to commit the changes to the device.
container.Dispose();
二.To read serialized data from a save game file
1.Create a StorageContainer to access the specified device.
IAsyncResult result = device.BeginOpenContainer("StorageDemo", null, null);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
StorageContainer container = device.EndOpenContainer(result);
// Close the wait handle.
result.AsyncWaitHandle.Close();
2.Call FileExists to determine if the save game exists.
// Check to see whether the save exists.
if (!container.FileExists(filename))
{
// If not, dispose of the container and return.
container.Dispose();
return;
}
3.Open a Stream object on the file by using the OpenFile method.
Stream stream = container.OpenFile(filename, FileMode.Open);
4.Create an XmlSerializer object, and then pass the type of the structure that defines your save game data.
5.Call Deserialize, and then pass the Stream object.
Deserialize returns a copy of the save game structure populated with the data from the save game file. (You will have to cast the return value from Object to your type.)
6.Close the Stream.
stream.Close();
7.Dispose the StorageContainer.
container.Dispose();