二进制序列化(保存并加载)

本文关键字:加载 保存 序列化 二进制 | 更新日期: 2023-09-27 17:56:18

我的问题是,我在旧程序中使用了这种二进制序列化结构,使用与保存和加载对象列表相同的格式。在新程序中,我没有收到任何错误,并且在运行程序并进入保存功能时,它会捕获异常并指出"无法保存文件"。当我手动打开 .Txt 文件,但再次运行程序时,数据不会重新加载。我只是想知道是否有人可以花几分钟时间查看代码,看看我是否缺少任何内容。

编辑* 我现在已经包括了包含教室列表和课堂类的显示类。 希望这有帮助

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;
namespace ExamAssignment
{
[Serializable]
public class SaveLoad
{
    public void Save(string filename, List<Classroom> objsave)                   
    {
        BinaryFormatter binFormatter = new BinaryFormatter();
        //point to the file's location 
        string strFileLocation = "SAVE.xml";
        // Gain code access to the file that we are going `
        // to write to 
        try
        {
            // Create a FileStream that will write data to file. 
            FileStream writerFileStream = new FileStream(strFileLocation,             FileMode.Create, System.IO.FileAccess.Write);
            binFormatter.Serialize(writerFileStream, objsave);
            // Close the writerFileStream when we are done. 
            writerFileStream.Close();
        }
        catch (Exception)
        {
            Console.WriteLine("Unable to save the file");
        }        
    }
    public List<Classroom> Load()
    {
        BinaryFormatter binFormatter = new BinaryFormatter();
        string strFileLocation = "SAVE.xml";// Check if we had previously Saved Results previously 
        List<Classroom> objLoad = new List<Classroom>();
        if (File.Exists(strFileLocation))
        {
            try
            {
                // Create a FileStream will gain read access to the data file. 
                FileStream readerFileStream = new FileStream(strFileLocation, FileMode.Open, System.IO.FileAccess.Read);// Reconstruct information of the Results from file. 
                objLoad = (List<Classroom>)
                binFormatter.Deserialize(readerFileStream);
                // Close the readerFileStream when we are done 
                readerFileStream.Close();
            }
            catch (Exception)
            {
                Console.WriteLine("There seems to be a file that contains the Classrooms but somehow there is a problem " + "with reading it.");// end try-catch 
            }
        }
        return objLoad;
        // end if 

..

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Collections;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Runtime.Serialization;
    using System.Xml;
    using System.Xml.Serialization;
namespace ExamAssignment
{
[Serializable]
public class Display
{
    Classroom C1 = new Classroom();
    public List<Classroom> ClassList;
    SaveLoad objSave = new SaveLoad();

    public Display()
    {
        ClassList = new List<Classroom>();

    }

    public void saving()
    {
        objSave.Save("SAVE.xml", ClassList);

    }
    public void Load()
    {
        ClassList = objSave.Load();

    }


    public void addClassroom()
    {
        Console.WriteLine("Please Enter the number of the classroom");
        int ClassNum = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("'nNow enter the module of the classroom");
        string ClassModule = Console.ReadLine();

        ClassList.Add(new Classroom(ClassNum, ClassModule));
        for (int i = 0; i < ClassList.Count(); i++)
        {
            Console.WriteLine("'nClass Number: {0}, Class Module: {1}", ClassNum, ClassModule);
        }

    }
    public void ViewClass()
    {

        Console.WriteLine("To view the students and teacher in a classroom please enter the class number");
        int selection = Convert.ToInt32(Console.ReadLine());
        int index = ClassList.FindIndex(item => selection == item.ClassNum);
        ClassList[index].ViewClassroom();


    }
    public void ViewClassrooms()
    {
        for (int i = 0; i < ClassList.Count; i++)
        {
            Console.WriteLine("'nClass Number: {0}, Class Module: {1}", ClassList[i].ClassNum, ClassList[i].ClassModule);
        }

    }

    public void AddStudent()
    {
        int repeat = 0;
        int RoomNumber = 0;
        Console.WriteLine("Please state the room number you wish to add the students to");
        RoomNumber = Convert.ToInt32(Console.ReadLine());
        int index = ClassList.FindIndex(item => RoomNumber == item.ClassNum);
        do
        {
            ClassList[index].AddStudent();
        Console.WriteLine("'nThank you, to add another student to the classroom press 1, or to exit press 0");
        repeat = Convert.ToInt32(Console.ReadLine());

        }
        while (repeat == 1);
    }
    public void removeStudent()
    {
        int RoomNumber = 0;
        Console.WriteLine("'nPlease state the room number you wish to remove the teacher from");
        RoomNumber = Convert.ToInt32(Console.ReadLine());
        int index = ClassList.FindIndex(item => RoomNumber == item.ClassNum);
        ClassList[index].RemoveStudent();

    }
    public void AddModule()
    {
        throw new System.NotImplementedException();
    }
    public void ViewModule()
    {
        throw new System.NotImplementedException();
    }
    public void AddTeacher()
    {

        int repeat = 0;
        int RoomNumber = 0;
        Console.WriteLine("Please state the room number you wish to add the Teacher to");
        RoomNumber = Convert.ToInt32(Console.ReadLine());
        int index = ClassList.FindIndex(item => RoomNumber == item.ClassNum);
        do
        {
            ClassList[index].AddTeacher();
        Console.WriteLine("'nThank you, to add another teacher to a classroom press 1, or to exit press 0");
        repeat = Convert.ToInt32(Console.ReadLine());
        }
        while (repeat == 1);
    }
        public void removeTeacher()
        {
            int RoomNumber = 0;
            Console.WriteLine("'nPlease state the room number you wish to remove the teacher from");
            RoomNumber = Convert.ToInt32(Console.ReadLine());
            int index = ClassList.FindIndex(item => RoomNumber == item.ClassNum);
            ClassList[index].RemoveTeacher();

        }

}

}

namespace ExamAssignment
{
[Serializable]
public class Classroom
{
    private int classNum;
    private string classModule;
    public Teacher t1;
    public List<Student> ClassStudents;
    public Display d1;
    public int selection;

    public Classroom(int newClassNum, string newClassModule)
    {
        ClassStudents = new List<Student>();
        Display d1 = new Display();
        classNum = newClassNum;
        classModule = newClassModule;
        //selection = Newselection;
    }
    public Classroom()
    {


    }

    public void AddStudent()
    {

            Console.WriteLine("Please enter the Student Name");
            string stuName = Console.ReadLine();
            Console.WriteLine("Now enter the student Id");
            int stuNum = Convert.ToInt32(Console.ReadLine());

            ClassStudents.Add(new Student(stuName, stuNum));

            for (int i = 0; i < ClassStudents.Count(); i++)
            {
                Console.WriteLine("'nStudent Name: {0}, Student ID: {1}", ClassStudents[i].Name, ClassStudents[i].StudentId);
            }

    }
    public void AddTeacher()
    {

        Console.WriteLine("Please enter the Teacher's name to add to the classroom");
        string teachName = Console.ReadLine();
        Console.WriteLine("Now enter the Teacher ID");
        int teachNum = Convert.ToInt32(Console.ReadLine());
        t1 = new Teacher(teachNum, teachName);

    }

    public void RemoveStudent()
    {
        int loop = 0;
        do
        {
            int j = 0;
            int selection = 0;

            for (int i = 0; i < ClassStudents.Count(); i++)
            {
                Console.WriteLine("'nStudent Name: {0}, Student ID: {1}, {2}", ClassStudents[i].Name, ClassStudents[i].StudentId, j);
                j = j + 1;
            }
            Console.WriteLine("'n'nTo remove a student please choose a number from the list or press 99 to exit");
            selection = Convert.ToInt32(Console.ReadLine());
            if (selection < 98)
            {
                loop = 1;
            }
            else
            {
                ClassStudents.RemoveAt(selection); 
            }
        }
        while (loop == 0);

    }

    public void RemoveTeacher()
    {
        int repeat = 0;
        do
        {
            Console.WriteLine("'nTeacher name:{0}, Teacher ID {1}'n", t1.name, t1.staffId);
            Console.WriteLine("To remove this teacher press 1 or to go back to the menu press 0");
            int selection = Convert.ToInt32(Console.ReadLine());
            if (selection == 1)
            {
                t1 = null;
                Console.WriteLine("'n Thank you, this teacher has been removed'n");
            }
            if (selection == 0)
            {
                repeat = 0;

            }
        }
        while (repeat == 1);
    }
    public void ViewClassroom()
    {

        if (ClassStudents != null)
        {
            foreach (Student s1 in ClassStudents)
            {
                Console.WriteLine("'n" + s1.name + " " + s1.studentId);
            }
        }

        if (t1 != null)
        {
            Console.WriteLine("'nTeacher name: {0}, Teacher ID {1}'n", t1.name, t1.staffId);
        }
        else
        {
            Console.WriteLine("there is no teacher associated with this classroom");
        }

    }
    public Teacher One
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }
    public Student Many
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }
    public Module onE
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    } 

    public int ClassNum
    {
        get
        {
            return classNum;
        }
        set
        {
            value = classNum;
        }
    }
    public string ClassModule
    {
        get
        {
            return classModule;
        }
        set
        {
            value = classModule;
        }
    }

}

}

二进制序列化(保存并加载)

使用 Serializable 属性标记您的类,因为这是序列化具有 BinaryFormatter 的类所必需的。

[Serializable]
public class Classroom
{
    /*...your class definition...*/
}