C# "在分析完成之前就遇到流结尾" 错误解决方法

C#在反序列化过程中

在分析完成之前就遇到流结尾(End of Stream encountered before parsing was completed?)

 

解决思路:

1、检查要序列化的对象,类是否标记 [Serializable]

2、添加 stream.Seek(0, SeekOrigin.Begin);方法来源如下图:

C#

C#

 

附:序列化及反序列化函数:

/// 
/// 序列化对象
/// 
/// 
internal static bool SerializeFile(object myObject, string filePath, out string errMsg)
{
     bool thisResult = true;
     try
     {
         IFormatter formatter = new BinaryFormatter();
         Stream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
         formatter.Serialize(stream, myObject);
         stream.Close();
         thisResult = true;
         errMsg = "";
     }
     catch (Exception ex)
     {
         thisResult = false;
         errMsg = ex.Message;
     }
     return thisResult;
}
/// 
        /// 反序列化对象
        /// 
        /// 
        /// 
        /// 
        /// 
        internal static bool AntiSerializeFile(string filePath, out object obj, out string errMsg)
        {
            bool thisResult = true;
            try
            {
                if (!File.Exists(filePath))
                {
                    errMsg = "文件不存在";
                    thisResult = false;
                    obj = null;
                }
                else
                {
                    IFormatter formatter = new BinaryFormatter();
                    Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
                    stream.Seek(0, SeekOrigin.Begin);
                    object myObj = formatter.Deserialize(stream);
                    stream.Close();
                    obj = myObj;
                    errMsg = "";
                }
            }
            catch (Exception ex)
            {
                thisResult = false;
                obj = null;
                errMsg = ex.Message;
            }
            return thisResult;
        }

 

你可能感兴趣的:(.Net,c#,在分析完成之前就遇到流结尾,End,of,Stream)