您的位置:首页 > 其它

XNA:保存数据到文件和从文件读取数据

2010-10-12 21:50 330 查看
基于最新的XNA Game Studio 4.0的环境下,因为XNA Game Studio 4.0以前的版本有些方法有变动。

前提:已经有一个正确的StorageDevice和定义好要保存的数据。

[Serializable]
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.

代码

string filename = "savegame.sav";
// 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.

// Open the file.
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.

CopyXmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));

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.)

SaveGameData data = (SaveGameData)serializer.Deserialize(stream);

6.Close the Stream.

// Close the file.
stream.Close();

7.Dispose the StorageContainer.

// Dispose the container.
container.Dispose();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐