c# - 将文件反序列化为 List C#

标签 c# list serialization deserialization

我正在尝试将包含对象的文件反序列化为对象列表 但对于某些列表如何仅适用于对象 这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            user lastuser = new user("First name", "Last name", "Username", "Password");
            FileStream ToStream = new FileStream("UsersDB.txt", FileMode.OpenOrCreate);
            BinaryFormatter Ser = new BinaryFormatter();
            List<user> ToUsers = new List<user>();

            try
            {
                ToUsers = (List<user>)Ser.Deserialize(ToStream); // this is to deserialize everything in the file to the list
                ToUsers.Add(lastuser); // here we are adding our object (which is lastuser) to the list
                Ser.Serialize(ToStream, ToUsers); // here we are serializing the list back to the file
            }
            catch (System.Runtime.Serialization.SerializationException)
            {//this is to catch the exception if the file was empty and there is nth to deserialize to the list
                ToUsers.Add(lastuser);
                Ser.Serialize(ToStream, ToUsers);
            }
            ToStream.Close();

            Console.WriteLine("ToUsers objects : " + ToUsers.Count());
            // this is to see how many objects does the list have
        }
    }
}

这是我正在序列化的类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;

namespace Test
{
    [Serializable]
    class user
    {
        private string Fname, Lname, Username, Password;

        public user()
        { }

        public user(string Fname, string Lname, string Username, string Password)
        {
            this.Fname = Fname;
            this.Lname = Lname;
            this.Username = Username;
            this.Password = Password;
        }

        public string GetUsername()
        {
            return Username;
        }

    }
}

当我运行它时,我得到列表的计数是 1。

再次运行我明白了 2.

运行 1000 次,您将得到 2 个。

我知道有问题所以请帮助我。

最佳答案

你在 try 中的代码是

  try
  {
      ToUsers = (List<user>)Ser.Deserialize(ToStream);
      ToUsers.Add(lastuser);
      Ser.Serialize(ToStream, ToUsers);
  }

上面代码中发生的事情是,在反序列化过程中,流位置指针被移动到文件末尾。因此,当您向后序列化时,包含这两个对象的列表将追加到文件末尾。

因此,新的文件结构是这样的

 +---------------------+-----------------------------------------------------+
 | List (1 user info)  |    List (2 user's info)                             |
 +---------------------+-----------------------------------------------------+

因此,当您下次反序列化时,您会再次获得包含一个用户详细信息的列表。

要覆盖现有数据,请使用以下命令将流位置指针重置为文件开头

ToStream.Seek(0, SeekOrigin.Begin);

因此,您的 try block 看起来像

  try
  {
      ToUsers = (List<user>)Ser.Deserialize(ToStream);
      ToStream.Seek(0, SeekOrigin.Begin);

      ToUsers.Add(lastuser);
      Ser.Serialize(ToStream, ToUsers);
  }

关于c# - 将文件反序列化为 List C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23326549/

相关文章:

c# - C# 和 java 之间的输出差异

c# - WCF 服务引用中的接口(interface)参数/返回类型

c++ - 如何在 C++11 中存储任意方法指针?

python - 如何为项目列表创建标签列表?

JSON 数据无法映射到我导出的接口(interface)?

java - 序列化一个java对象

c# - ASP.Net MVC3 模型绑定(bind) IEnumerable<T> 与编辑器模板

python - 从 python 列表中删除重复的 JSON 对象

dart - Dart中抽象类型的反序列化

c# - 如何在将数据写入 Excel 时制作正确的日期格式