SaveGame.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using Microsoft.Xna.Framework.Storage;
  3. using System.Xml.Serialization;
  4. using System.IO;
  5. namespace Microsoft.Xna.Samples.Storage
  6. {
  7. [Serializable]
  8. public struct SaveGame
  9. {
  10. public string Name;
  11. public int HiScore;
  12. public DateTime Date;
  13. [NonSerialized]
  14. public int DontKeep;
  15. }
  16. public class SaveGameStorage
  17. {
  18. public void Save(SaveGame sg)
  19. {
  20. StorageDevice device = StorageDevice.ShowStorageDeviceGuide();
  21. // Open a storage container
  22. StorageContainer container = device.OpenContainer("TestStorage");
  23. // Get the path of the save game
  24. string filename = Path.Combine(container.Path, "savegame.xml");
  25. // Open the file, creating it if necessary
  26. FileStream stream = File.Open(filename, FileMode.OpenOrCreate);
  27. // Convert the object to XML data and put it in the stream
  28. XmlSerializer serializer = new XmlSerializer(typeof(SaveGame));
  29. serializer.Serialize(stream, sg);
  30. // Close the file
  31. stream.Close();
  32. // Dispose the container, to commit changes
  33. container.Dispose();
  34. }
  35. public SaveGame Load()
  36. {
  37. SaveGame ret = new SaveGame();
  38. StorageDevice device = StorageDevice.ShowStorageDeviceGuide();
  39. // Open a storage container
  40. StorageContainer container = device.OpenContainer("TestStorage");
  41. // Get the path of the save game
  42. string filename = Path.Combine(container.Path, "savegame.xml");
  43. // Check to see if the save exists
  44. if (!File.Exists(filename))
  45. // Notify the user there is no save
  46. return ret;
  47. // Open the file
  48. FileStream stream = File.Open(filename, FileMode.OpenOrCreate,
  49. FileAccess.Read);
  50. // Read the data from the file
  51. XmlSerializer serializer = new XmlSerializer(typeof(SaveGame));
  52. ret = (SaveGame)serializer.Deserialize(stream);
  53. // Close the file
  54. stream.Close();
  55. // Dispose the container
  56. container.Dispose();
  57. return ret;
  58. }
  59. }
  60. }