Generic Save Object

 

I wrote this class to quickly save lists of custom structs for a program I am currently working on. I thought I would share it with others that might need a quick class to save objects to xml and read them back in using Isolated Storage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
 
public class IsolatedFile<T>
{
    private IsolatedStorageFile isoStore;
    private string _fileName = "";
 
    /// <summary>
    /// Create a new Isolated File Class
    /// </summary>
    /// <param name="FileName">The file name to open/save</param>
    public IsolatedFile(string FileName)
    {
        isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
        _fileName = FileName;
    }
 
    /// <summary>
    /// The FileName that was set when this class was created
    /// </summary>
    public string FileName
    {
        get
        {
            return _fileName;
        }
    }
 
    /// <summary>
    /// If the file exists
    /// </summary>
    public bool Exists
    {
        get
        {
            if (isoStore.GetFileNames(_fileName).Length == 1) { return true; }
            return false;
        }
    }
 
    /// <summary>
    /// Saves the object in XML Serialization
    /// </summary>
    /// <param name="Object">Object to save</param>
    /// <returns>True if file was saved.</returns>
    public bool Save(T Object)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
 
            IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(_fileName, FileMode.Create, isoStore);
 
            serializer.Serialize(isoStream, Object);
 
            isoStream.Close();
 
            return true;
        }
        catch { }
        return false;
    }
 
    /// <summary>
    /// Loads the saved object.
    /// </summary>
    /// <returns>Return the objects from the saved XML</returns>
    public T Load()
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
 
        IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(_fileName, FileMode.Open, isoStore);
 
        T tempObject = (T)serializer.Deserialize(isoStream);
 
        isoStream.Close();
 
        return tempObject;
 
    }
 
 
}
Robert M. Meffe (0 Posts)


Leave a Reply