Jypeli  5
The simple game programming library
SaveState.cs
Siirry tämän tiedoston dokumentaatioon.
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Xml;
6 using System.IO;
7 
8 namespace Jypeli
9 {
10  public class SaveState : IDisposable
11  {
12  public StorageFile File { get; private set; }
13 
14  private XmlWriter writer;
15  private XmlWriterSettings settings;
16  private bool closed = false;
17 
18  internal SaveState( FileManager manager, string fileName )
19  {
20  File = manager.Open( fileName, true );
21  settings = new XmlWriterSettings();
22  settings.ConformanceLevel = ConformanceLevel.Document;
23  settings.Encoding = Encoding.UTF8;
24  settings.Indent = true;
25  BeginWriteXml();
26  writer.WriteStartDocument();
27  writer.WriteStartElement( "State" );
28  }
29 
30  internal void BeginWriteXml()
31  {
32  if ( closed )
33  throw new IOException( "Tried to write to a closed state file." );
34 
35  if ( writer == null )
36  writer = XmlWriter.Create( File.Stream, settings );
37  }
38 
39  public void Dispose()
40  {
41  EndSave();
42  }
43 
44  public void Save<T>( object obj, string name )
45  {
46  Save( obj, typeof( T ), name );
47  }
48 
49  public void Save( object obj, Type objType, string name )
50  {
51  BeginWriteXml();
52  writer.WriteStartElement( "Object" );
53  writer.WriteAttributeString( "Name", name );
54  writer.WriteAttributeString( "TypeAssembly", objType.Assembly.FullName );
55  writer.WriteAttributeString( "Type", objType.Name );
56  File.SaveData( writer, objType, obj, false );
57  writer.WriteEndElement();
58  }
59 
60  public void EndSave()
61  {
62  if ( !closed )
63  {
64  BeginWriteXml();
65  writer.WriteEndElement();
66  writer.WriteEndDocument();
67  closed = true;
68  }
69 
70  if ( writer != null )
71  {
72  writer.Close();
73  writer = null;
74  }
75 
76  if ( File != null )
77  {
78  File.Close();
79  File = null;
80  }
81  }
82  }
83 }
StorageFile File
Definition: SaveState.cs:12
void Save(object obj, Type objType, string name)
Definition: SaveState.cs:49
abstract StorageFile Open(string fileName, bool write)
void EndSave()
Definition: SaveState.cs:60
void Save< T >(object obj, string name)
Definition: SaveState.cs:44
void Dispose()
Definition: SaveState.cs:39