如何使用FileStream C#将文件加载到列表中,然后加载到列表框中?

时间:2015-12-29 18:15:54

标签: c# load external filestream

enter image description here

上面的图片只显示下面的代码,您可以使用其中任何一个来帮助我解决我的噩梦。谢谢小伙子

List<IpayableStaff> employeeList = new List<IpayableStaff>();

private void LoadData()
        {
            FileStream inFile;
            BinaryFormatter bformatter = new BinaryFormatter();

            if (File.Exists(filename))
            {
                inFile = new FileStream(filename, FileMode.Open, FileAccess.Read);

                while (inFile.Position < inFile.Length)
                {
                    IpayableStaff load = (IpayableStaff)bformatter.Deserialize(inFile);
                    employeeList.Add(load);
                    lstEmployees.Items.Add(load);
                }

                inFile.Close();
            }
        }

private void SaveData()
{        
    FileStream outFile;

    BinaryFormatter bformatter = new BinaryFormatter();

    if (lstEmployees.Items.Count > 0)
        {
          //opening the file in order to write in to it
          outFile = new FileStream(filename, FileMode.Create, FileAccess.Write);

         for (int i = 0; i < lstEmployees.Items.Count; i++)
         {
            //write on file via serialization
            bformatter.Serialize(outFile, lstEmployees.Items[i]);
         }

          //closing the file
          outFile.Close();
     }
 }

有一个错误,但我看不到它,请帮助我已经尝试了很多可能的解决方案,但直到现在还没有

1 个答案:

答案 0 :(得分:1)

错误消息Unable to cast object of type System.String to type Assignment.IpayableStaff非常清楚地表明您序列化的类型与您反序列化的类型不同。

此外,如果可以同时对整个列表进行反序列化,那么一次序列化一条记录是个坏主意。

从评论更新:...bformatter.Serialize(outFile, lstEmployees.Items[i]);您正在序列化ListBox个对象(逐个),然后尝试将它们反序列化为其他内容(IPayableStaff)。您可能已将IPayableStaff存储到Items(我们无法看到的代码),但在序列化时您没有将它们强制转换。

解决方法

// some data
critters = new List<Animal>();
string file = @"C:\Temp\Animals.bin";

Animal animal = new Animal("ziggy","feline", 3.14);
critters.Add(animal);
critters.Add(new Animal("rover", "canine", 1.23));
critters.Add(new Animal("Gizmo", "muhwai", .56));

SaveData(file, critters);

List<Animal> newALst = LoadData(file);
// use the List<T> as listbox datasource
lb1.DataSource = newALst;

您在ToString()覆盖Animal/IPayableStaff覆盖的任何内容都将显示在列表框中(和调试!):

public override string ToString()
{
    return string.Format("{0}  ({1})",Name, Species);
}

enter image description here

保存/加载方法:

private void SaveData(string fil, List<Animal> animalList)
{   
    // serialize entire list
    using (FileStream fs = new FileStream(fil, FileMode.OpenOrCreate))
    {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fs, animalList);
    }
}

private List<Animal> LoadData(string filename)
{
    List<Animal> newLst = new List<Animal>();

    // deserialize entire list and return it
    using (FileStream fs = new FileStream(filename, FileMode.Open))
    {
        BinaryFormatter bf = new BinaryFormatter();
        newLst= (List<Animal>)bf.Deserialize(fs);
    }
    return newLst;
}

BinaryFormatter知道Type serialized,因为它将类型元数据写入文件。这会导致您获得的错误,并且通过逐个执行此操作,您可以轻松地将文件丢弃,尝试每次只保存一条记录而不是所有记录。