I have this code here where I am trying to save each field in an instance of a class to a separate file. I have it all written out, but something just does not look right about it. The problem is that it doesn’t reference the instance, which contains the data, just the type. And that to me doesn’t quite seem right. I am using System.Reflection. Now, how do I reference the instance? Or am I already and don’t know it. Here is my code:
public static void Save(appData data)
{
string filename;
// this does not accept the variable "data", only the class spec "appData"
var fields = typeof(appData).GetFields(BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
try
{
filename = (string)field.GetValue("dataFile");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
dataStream = new FileStream(filename,
FileMode.Truncate, FileAccess.Write,
FileShare.Read);
serial.Serialize(dataStream, field );
dataStream.Flush();
dataStream.Close();
dataStream = null;
}
}
Although your code is incomplete, I think I can tell what you’re trying to do.
Your example is actually serializing the
FieldInfoobject, not the fields. You want to replace:filename = (string)field.GetValue("dataFile");with:
filename = field.Name;Also replace:
serial.Serialize(dataStream, field );with:
serial.Serialize(dataStream, field.GetValue(data);Just make sure that all of your fields are able to be serialized by your
serialobject.