用于保存和加载对象的通用类库






1.95/5 (9投票s)
一个通用的类库,用于使用XML或二进制格式在文件中保存和加载对象。
引言
所有程序员都需要保存他们的应用程序数据或状态,以便稍后恢复它们。但是,编写将数据保存到文件和加载数据的方法有时会花费大量时间。这个类库可以节省您大量的时间来保存和加载数据。
背景
如果您想保存对象的状态,这意味着您应该将对象的所有成员、字段和属性值保存到文件中,然后稍后恢复它们的值。
使用代码
这个类有两个名为“SaveData
”和“LoadData
”的方法。这些方法需要的参数是您想要保存的对象、您想要保存对象数据到的路径,以及保存格式的类型:XML或二进制。
namespace BabakTajalliNezhad.Tools
{
public class ObjectController
{
DataSet Result = new DataSet("Object Save & Load - " +
"Programmed by Babak Tajalli Nezhad");
DataTable CurrentTable;
public enum SaveType { XML, Binary };
#region .:: Object Load Methods ::.
//------------------------Load Methods----------------------------------\\
/// <summary>
/// Used to Load Data from a file in to an instance of an object
/// </summary>
/// <param name="Target">The instance of an object
/// which you want to load the data into</param>
/// <param name="Path">The File path of where
/// you saved your object</param>
/// <param name="HowToSave">specifies the type of save
/// operation binary or xml</param>
[Description("Used to Load Data from a file in to an instance of an object")]
public void LoadData(object Target, string Path,SaveType HowToSave)
{
Result.Clear();
if (HowToSave == SaveType.Binary)
{
string FileContent = System.IO.File.ReadAllText(Path);
string XMLContent = "";
for (int e = 0; e < FileContent.Length; e += 10)
{
XMLContent += FileContent[e];
}
System.IO.StreamWriter TempWriter =
new System.IO.StreamWriter(Environment.SystemDirectory +
@"\temp.xml");
TempWriter.Write(XMLContent);
TempWriter.Close();
Result.ReadXml(Environment.SystemDirectory + @"\temp.xml");
System.IO.File.Delete(Environment.SystemDirectory + @"\temp.xml");
}
else
{
Result.ReadXml(Path);
}
Type ObjectType = Target.GetType();
System.Reflection.PropertyInfo[] ObjectProperties =
ObjectType.GetProperties();
System.Reflection.FieldInfo[] ObjectFields = ObjectType.GetFields();
//string Result
CurrentTable = Result.Tables[ObjectType.Name + "_Fields"];
for (int i = 0; i < ObjectFields.Length; i++)
{
try
{
xmlToField(ObjectFields[i], Target);
}
catch { }
}
CurrentTable = Result.Tables[ObjectType.Name + "_Properties"];
for (int i = 0; i < ObjectProperties.Length; i++)
{
try
{
xmlToProperty(ObjectProperties[i], Target);
}
catch { }
}
}
private object LoadData(string Name)
{
foreach (DataRow Dr in CurrentTable.Rows)
{
if (Dr["Name"].ToString() == Name)
{
return Dr["Value"];
}
}
return null;
}
private void xmlToField(System.Reflection.FieldInfo Field, object Target)
{
try
{
Type TargetType = Field.FieldType;
if (!TargetType.IsPrimitive)
{
if (TargetType.IsSerializable)
{
LoadSerializedData(Field.GetValue(Target) as Array,
Field.ReflectedType.FullName + "." + Field.Name);
}
System.Reflection.FieldInfo[] TargetFields = TargetType.GetFields();
System.Reflection.PropertyInfo[] TargetProperties =
TargetType.GetProperties();
for (int i = 0; i < TargetFields.Length; i++)
{
xmlToField(TargetFields[i], Field.GetValue(Target));
}
for (int j = 0; j < TargetProperties.Length; j++)
{
propertyToxml(TargetProperties[j], Field.GetValue(Target));
}
}
try
{
object Value = LoadData(Field.ReflectedType.FullName +
"." + Field.Name);
Field.SetValue(Target, Convert.ChangeType(Value, Field.FieldType));
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
catch { }
}
private void LoadSerializedData(Array Target, string Caller)
{
try
{
for (int j = 0; j < Target.Length; j++)
{
if (Target.GetValue(j) != null)
{
Type ObjectType = Target.GetValue(j).GetType();
if (!ObjectType.IsPrimitive)
{
System.Reflection.FieldInfo[] ObjectFields =
ObjectType.GetFields();
System.Reflection.PropertyInfo[] ObjectProperties =
ObjectType.GetProperties();
for (int i = 0; i < ObjectFields.Length; i++)
{
xmlToField(ObjectFields[i], Target.GetValue(j));
}
for (int i = 0; i < ObjectProperties.Length; i++)
{
xmlToProperty(ObjectProperties[i], Target.GetValue(j));
}
}
try
{
object Value = LoadData(Caller + "[" + j.ToString() + "]");
Target.SetValue(Convert.ChangeType(Value,
Target.GetValue(j).GetType()), j);
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
}
}
catch { }
}
private void xmlToProperty(System.Reflection.PropertyInfo Property, object Target)
{
try
{
if (Property.CanWrite && Property.CanWrite)
{
Type TargetProperty = Property.GetType();
System.Reflection.PropertyInfo[] TargetProperties =
TargetProperty.GetProperties();
System.Reflection.FieldInfo[] TargetFields = TargetProperty.GetFields();
for (int i = 0; i < TargetProperties.Length; i++)
{
xmlToProperty(TargetProperties[i], Property.GetValue(Target, null));
}
for (int j = 0; j < TargetFields.Length; j++)
{
xmlToField(TargetFields[j], Property.GetValue(Target, null));
}
try
{
object Value = LoadData(Property.ReflectedType.FullName +
"." + Property.Name);
Property.SetValue(Target, Convert.ChangeType(Value,
Property.PropertyType), null);
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
}
catch { }
}
#endregion
#region .:: Object Save Methods ::.
//-------------------------Save Methods----------------------------------\\
/// <summary>
/// Used to Save an instance of an object in to a file
/// </summary>
/// <param name="Target">The instance of an object which you want to save</param>
/// <param name="Path">The File path of where you want to save your object</param>
/// <param name="HowToSave">specifies the type of save operation binary or xml</param>
[Description("Used to Save an instance of an object in to a file")]
public void SaveData(object Target, string Path,SaveType HowToSave)
{
Type ObjectType = Target.GetType();
System.Reflection.PropertyInfo[] ObjectProperties = ObjectType.GetProperties();
System.Reflection.FieldInfo[] ObjectFields = ObjectType.GetFields();
//string Result
DataTable ObjectTable = new DataTable(ObjectType.Name + "_Fields");
SetTableFields(ref ObjectTable);
CurrentTable = ObjectTable;
for (int i = 0; i < ObjectFields.Length; i++)
{
try
{
fieldsToxml(ObjectFields[i], Target);
}
catch { }
}
Result.Tables.Add(CurrentTable);
DataTable PropertyTable = new DataTable(ObjectType.Name +
"_Properties");
SetTableFields(ref PropertyTable);
CurrentTable = PropertyTable;
for (int i = 0; i < ObjectProperties.Length; i++)
{
try
{
propertyToxml(ObjectProperties[i], Target);
}
catch { }
}
Result.Tables.Add(CurrentTable);
if (HowToSave == SaveType.XML)
{
Result.WriteXml(Path);
}
else
{
string XMLObject = Result.GetXml();
System.IO.StreamWriter MyWriter =
new System.IO.StreamWriter(Path);
Random MyRandomNumbr = new Random();
for (int e = 0; e < XMLObject.Length; e++)
{
MyWriter.Write(XMLObject[e]);
MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
}
MyWriter.Close();
}
}
private void SetTableFields(ref DataTable Table)
{
Table.Columns.Add("Name");
Table.Columns.Add("Value");
}
private void SaveData(string Name, object Value)
{
CurrentTable.Rows.Add(new object[] { Name, Value });
}
private void fieldsToxml(System.Reflection.FieldInfo Field, object Target)
{
try
{
Type TargetType = Field.FieldType;
if (!TargetType.IsPrimitive)
{
if (TargetType.IsSerializable)
{
SaveSerializedData(Field.GetValue(Target) as Array,
Field.ReflectedType.FullName + "." + Field.Name);
}
System.Reflection.FieldInfo[] TargetFields = TargetType.GetFields();
System.Reflection.PropertyInfo[] TargetProperties =
TargetType.GetProperties();
for (int i = 0; i < TargetFields.Length; i++)
{
fieldsToxml(TargetFields[i], Field.GetValue(Target));
}
for (int j = 0; j < TargetProperties.Length; j++)
{
propertyToxml(TargetProperties[j], Field.GetValue(Target));
}
}
SaveData(Field.ReflectedType.FullName + "." +
Field.Name, Field.GetValue(Target));
}
catch { }
}
private void SaveSerializedData(Array Target, string Caller)
{
try
{
for (int j = 0; j < Target.Length; j++)
{
if (Target.GetValue(j) != null)
{
Type ObjectType = Target.GetValue(j).GetType();
if (!ObjectType.IsPrimitive)
{
System.Reflection.FieldInfo[] ObjectFields =
ObjectType.GetFields();
System.Reflection.PropertyInfo[] ObjectProperties =
ObjectType.GetProperties();
for (int i = 0; i < ObjectFields.Length; i++)
{
fieldsToxml(ObjectFields[i], Target.GetValue(j));
}
for (int i = 0; i < ObjectProperties.Length; i++)
{
propertyToxml(ObjectProperties[i], Target.GetValue(j));
}
}
SaveData(Caller + "[" + j.ToString() +
"]", Target.GetValue(j));
}
}
}
catch { }
}
private void propertyToxml(System.Reflection.PropertyInfo Property, object Target)
{
try
{
if (Property.CanWrite && Property.CanWrite)
{
Type TargetProperty = Property.GetType();
System.Reflection.PropertyInfo[] TargetProperties =
TargetProperty.GetProperties();
System.Reflection.FieldInfo[] TargetFieds = TargetProperty.GetFields();
for (int i = 0; i < TargetProperties.Length; i++)
{
propertyToxml(TargetProperties[i], Property.GetValue(Target, null));
}
for (int j = 0; j < TargetFieds.Length; j++)
{
fieldsToxml(TargetFieds[j], Property.GetValue(Target, null));
}
SaveData(Property.ReflectedType.FullName + "." +
Property.Name, Property.GetValue(Target, null));
}
}
catch { }
}
#endregion
}
}