Alright, I have a class “EIR” which is a List based from its base class “ExpenseReport” as such:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;
using System.Linq;
using System.Text;
namespace Payroll
{
[Serializable]
public class EIR : List<ExpenseItem>
{
public void WriteToFile(string filename)
{
try
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream("D:\\myExpensesUpdated.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, filename);
stream.Close();
}
catch (Exception ex)
{
Console.WriteLine("Unable to serialize Expenses: {0}", ex.Message);
}
}
public static EIR ReadFromFile(string filename)
{
EIR iRost = new EIR();
try
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream("D:\\myExpensesUpdated.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
iRost = (EIR)formatter.Deserialize(stream);
}
catch (Exception ex)
{
Console.WriteLine("Unable to deserialize Expenses: {0}", ex.Message);
}
return iRost;
}
}
}
}
This ReadFromFile part is where I’m having a problem:
In the main program, this portion tries to call ReadFromFile and display newly updated items but I get the error “Unable to cast object of type ‘System.String’ to type ‘Payroll.EIR'”.
try
{
EIR expensesUpdated = EIR.ReadFromFile("D:\\myExpensesUpdated.bin");
foreach (var e in expensesUpdated) Console.WriteLine("Updated: {0}", e.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
How do I get the iRost to cast to the Payroll.EIR which is a class? Is there some way to convert a serialized string to a class?
Your problem is already in
WriteToFilefunction where you are actually serializing the filename instead of the class. I didn’t try it but this should work:Are you sure it’s a good idea to silently catch all exceptions and just write a message to console?