test2.xml (Test Case 1):
<?xml version="1.0"?>
<DerivedClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<InstanceID>2</InstanceID>
<Number>300.900024</Number>
<Description>This is a test.</Description>
<TestState>DONE</TestState>
<TestTime>2010-12-08T02:23:50.265625+08:00</TestTime>
<StrFont>Times New Roman, 10pt</StrFont>
</DerivedClass>
public static void TSerialize(object theObject, string sFileName)
{
BinaryFormatter btFormatter = new BinaryFormatter();
FileStream theFileStream = new FileStream(sFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
btFormatter.Serialize(theFileStream, theObject);
theFileStream.Close();
}
public static object TDeSerialize(Type theType, string sFileName)
{
if (sFileName == null || sFileName == "" || !File.Exists(sFileName))
{
return null;
}
FileStream theFileStream = new FileStream(sFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryFormatter btFormatter = new BinaryFormatter();
object theObj = btFormatter.Deserialize(theFileStream);
theFileStream.Close();
return theObj;
}
As well as the functions using a simple encryption and decryption method:
public static void SerializeWithEncrypt(object theObject, string sFileName)
{
MemoryStream theMS = new MemoryStream();
BinaryFormatter btFormatter = new BinaryFormatter();
btFormatter.Serialize(theMS, theObject);
theMS.Seek(0, SeekOrigin.Begin);
byte[] temp = theMS.ToArray();
temp = Encrypt(temp);
//Output to a file.
FileStream theFileStream = new FileStream(sFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
BinaryWriter theBW = new BinaryWriter(theFileStream);
theBW.Write(temp, 0, temp.Length);
theBW.Close();
theFileStream.Close();
theMS.Dispose();
}
public static object DeSerializeWithDecrypt(string sFileName)
{
if (sFileName == null || sFileName == "" || !File.Exists(sFileName))
{
return null;
}
byte[] temp = File.ReadAllBytes(sFileName);
temp = Decrypt(temp);
MemoryStream theMS = new MemoryStream(temp);
BinaryFormatter btFormatter = new BinaryFormatter();
object theObj = btFormatter.Deserialize(theMS);
theMS.Dispose();
return theObj;
}
The Configuration class is implemented as singleton. The persistent data is loaded upon the first time call to create the single instance:
[Serializable]
public sealed class Configuration
{
private static Configuration instance = null;
private Configuration()
{
}
public static Configuration Instance
{
get
{
if (instance == null)
{
instance = (Configuration)Utility.TDeSerialize("test.dat");
}
if (instance == null)
{
instance = new Configuration();
}
return instance;
}
}
…
…
All the above code can be found in the attached package.
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)