Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 序列化/反序列化。正在尝试从文件中写入和读取_C#_Serialization_Deserialization - Fatal编程技术网

C# 序列化/反序列化。正在尝试从文件中写入和读取

C# 序列化/反序列化。正在尝试从文件中写入和读取,c#,serialization,deserialization,C#,Serialization,Deserialization,我正试图读写一个文件。 对于第一部分,将对象列表写入二进制文件,我使用序列化成功地实现了这一点 问题是当我尝试使用反序列化从文件读回对象列表时。每次运行解决方案时,都会出现运行时错误 守则: using System; using System.IO; using MileStone1Fin.LogicLayer; using System.Collections.Generic; using System.Runtime.Serialization; using System.Runt

我正试图读写一个文件。 对于第一部分,将对象列表写入二进制文件,我使用序列化成功地实现了这一点

问题是当我尝试使用反序列化从文件读回对象列表时。每次运行解决方案时,都会出现运行时错误

守则:

    using System;
using System.IO;
using MileStone1Fin.LogicLayer;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;

namespace MileStone1Fin.PersistentLayer
{
    public class UserHandler
    {

        public UserHandler()
        {
        }

        public void addNewUser(List<User> users)
        {
            Stream myFileStream = File.Create("UsersData.bin");

            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(myFileStream, users);

            Console.WriteLine("5535");
            myFileStream.Close();


            List<User> newUsers1 = null;

            if (File.Exists("UsersData.bin"))
            {
                Stream myFileStream1 = File.OpenRead("UsersData.bin");

                BinaryFormatter bf1 = new BinaryFormatter();

                newUsers1 = (List<User>)bf1.Deserialize(myFileStream1);//this line marked as the problem one according to visual studio

                myFileStream1.Close();
            }
        }
    }
}
使用系统;
使用System.IO;
使用MileStone1Fin.LogicLayer;
使用System.Collections.Generic;
使用System.Runtime.Serialization;
使用System.Runtime.Serialization.Formatters.Binary;
使用Newtonsoft.Json;
命名空间MileStone1Fin.PersistentLayer
{
公共类用户处理程序
{
公共用户处理程序()
{
}
public void addNewUser(列出用户)
{
Stream myFileStream=File.Create(“UsersData.bin”);
BinaryFormatter bf=新的BinaryFormatter();
序列化(myFileStream,用户);
控制台写入线(“5535”);
myFileStream.Close();
List newUsers1=null;
if(File.Exists(“UsersData.bin”))
{
Stream myFileStream1=File.OpenRead(“UsersData.bin”);
BinaryFormatter bf1=新的BinaryFormatter();
newUsers1=(List)bf1.Deserialize(myFileStream1);//根据visual studio,这一行被标记为问题行
myFileStream1.Close();
}
}
}
}
第38行是有问题的一行 发出调用的代码:

public void registration(String nickname, String groupID)
    {
        if(checkUserValidity(nickname, groupID))
        {
            User newUser = new User(nickname, groupID);
            users.Add(newUser);
            userHandler.addNewUser(users);




User class:
System.Reflection.TargetInvocationExeption - the runtime error


    using System;
using Newtonsoft.Json;
using MileStoneClient.CommunicationLayer;
using MileStone1Fin.PersistentLayer;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace MileStone1Fin.LogicLayer
{
    ///<summary>
    /// This class taking care for the functionallity of the user objects.
    /// The user class will be part of the Logic layer
    /// </summary>
    [Serializable()]
    public class User : ISerializable
    {
        private static UserHandler userHandler = new UserHandler();
        private String nickname { get; set; }
        private String groupID { get; set; }
        private bool status { get; set; }
        DateTime lastSeen { get; set; }

        public User(String nickname, String groupID) //The User class constructor
        {
            this.nickname = nickname;
            this.groupID = groupID;
            this.lastSeen = DateTime.Now;
            this.status = false;

        }

        /*public Message send(String msg) //Creates a Imessage object, return a Message object contains GUID, time, user
        {                               //information, message body
            IMessage message = Communication.Instance.Send(ChatRoom.url, this.groupID, this.nickname, msg);//sends the neccesary details to the server
            return new Message(message);
        }*/

        public void logout()
        {
            this.status = false;
            //Console.WriteLine(this.nickname + "You were disconnected from the server");
            lastSeen = DateTime.Now;
            //Console.WriteLine(lastSeen);
            //need to write into file
        }

        private bool isOnline()
        {
            return this.status;
        }

        public void lastSeenDate()
        {
            if (isOnline())
                Console.WriteLine("Online now");
            else
                Console.WriteLine(lastSeen.ToString());
        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Nickname", nickname);
            info.AddValue("GroupId", groupID);
            info.AddValue("LastSeen", lastSeen);
            info.AddValue("Status", status);
        }

        public User(SerializationInfo info, StreamingContext context)
        {
            nickname = (string)info.GetValue("Name", typeof(string));
            groupID = (string)info.GetValue("GroupId", typeof(string));
            lastSeen = (DateTime)info.GetValue("LastSeen", typeof(DateTime));
            status = (Boolean)info.GetValue("Status", typeof(Boolean));
        }
    }
}
公共无效注册(字符串昵称、字符串组ID)
{
if(检查用户有效性(昵称、组ID))
{
User newUser=新用户(昵称,组ID);
users.Add(newUser);
userHandler.addNewUser(用户);
用户类别:
System.Reflection.TargetInvocationException-运行时错误
使用制度;
使用Newtonsoft.Json;
使用MileStoneClient.CommunicationLayer;
使用MileStone1Fin.PersistentLayer;
使用System.Runtime.Serialization;
使用System.Runtime.Serialization.Formatters.Binary;
命名空间MileStone1Fin.logicalayer
{
///
///此类负责用户对象的功能性。
///用户类将是逻辑层的一部分
/// 
[可序列化()]
公共类用户:ISerializable
{
私有静态UserHandler UserHandler=new UserHandler();
私有字符串昵称{get;set;}
私有字符串groupID{get;set;}
私有布尔状态{get;set;}
DateTime lastSeen{get;set;}
公共用户(字符串昵称,字符串组ID)//用户类构造函数
{
this.昵称=昵称;
this.groupID=groupID;
this.lastSeen=DateTime.Now;
这个.status=false;
}
/*公共消息发送(字符串msg)//创建Imessage对象,返回包含GUID、时间、用户的消息对象
{//信息,消息正文
IMessage message=Communication.Instance.Send(ChatRoom.url,this.groupID,this.昵称,msg);//将必要的详细信息发送到服务器
返回新消息(消息);
}*/
公开作废注销()
{
这个.status=false;
//Console.WriteLine(this.昵称+“您已断开与服务器的连接”);
lastSeen=DateTime.Now;
//控制台。写入线(上次看到);
//需要写入文件吗
}
私有bool isOnline()
{
返回此状态;
}
公共空间最后一次访问日期()
{
if(isOnline())
Console.WriteLine(“现在在线”);
其他的
Console.WriteLine(lastSeen.ToString());
}
public void GetObjectData(SerializationInfo信息、StreamingContext上下文)
{
信息增值(“昵称”,昵称);
info.AddValue(“GroupId”,GroupId);
info.AddValue(“LastSeen”,LastSeen);
信息添加值(“状态”,状态);
}
公共用户(SerializationInfo、StreamingContext上下文)
{
昵称=(字符串)info.GetValue(“名称”,typeof(字符串));
groupID=(string)info.GetValue(“groupID”,typeof(string));
lastSeen=(DateTime)info.GetValue(“lastSeen”,typeof(DateTime));
status=(Boolean)info.GetValue(“status”,typeof(Boolean));
}
}
}

问题在于如何使用序列化来命名事物,将
昵称
序列化,并尝试将其读出为
名称
。最安全的做法是从属性中获取正确的名称:

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue(nameof(nickname), nickname);
        info.AddValue(nameof(groupID), groupID);
        info.AddValue(nameof(lastSeen), lastSeen);
        info.AddValue(nameof(status), status);
    }

    public User(SerializationInfo info, StreamingContext context)
    {
        nickname = (string)info.GetValue(nameof(nickname), typeof(string));
        groupID = (string)info.GetValue(nameof(groupID), typeof(string));
        lastSeen = (DateTime)info.GetValue(nameof(lastSeen), typeof(DateTime));
        status = (Boolean)info.GetValue(nameof(status), typeof(Boolean));
    }
}

当您将属性重命名为.NET标准时,它还有一个额外的好处,它也会自动重命名您的代码。如果您重命名某个内容,然后尝试加载旧文件,则可能会导致问题,因此请小心,但至少这样,您的代码中不会出现神奇的字符串。通过将版本信息写入序列化流并基于版本进行反序列化,可以避免上述问题sion.

您得到了什么运行时错误?在哪一行?请同时显示您的
用户
类。我刚刚编辑了question@Sprint21该错误必须包含堆栈跟踪。您可以包含该跟踪吗?错误不止于此,它还应该附带某种描述或消息。
昵称=(字符串)info.GetValue(“Name”,typeof(string));
可能是您的问题,您正在序列化“昵称”,但试图读取“Name”。