反序列化出现异常:SerializationException 在分析完成之前就遇到流结尾

    /// <summary>
    /// 处理配置文件类
    /// </summary>
    public class ConfigClass
    {
        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="strPath"></param>
        /// <returns></returns>
        public UserConfig ReadUserConfig(string strPath)
        {
            UserConfig config = new UserConfig();
            MemoryStream ms = new MemoryStream ();
            try
            {
                using (FileStream fs = new FileStream(strPath,FileMode.Open,FileAccess.Read))
                {
                    byte[] buffer = new byte[fs.Length];
                    int length = fs.Read(buffer, 0, (int)fs.Length);
                    fs.Close(); 
                    ms.Write(buffer, 0, length); // 将字节写入内存流以备序列化使用
                    ms.Flush(); 
                }
            }
            catch (IOException ioex)
            {
                throw new MyException("读取配置信息失败!", ioex, "ConfigClass", "Client");
            }

            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                //执行反序列化之前需要将流的指针移动到开头
                //ms.Seek(0, SeekOrigin.Begin);
                ms.Position = 0;
                config = formatter.Deserialize(ms) as UserConfig;
            }
            catch (SerializationException ex)
            {
                throw new MyException("反序列化失败,配置文件已损坏!", ex, "ConfigClass", "Client");
            }
            catch (System.Security.SecurityException sex)
            {
                throw new MyException("反序列化失败,配置文件已损坏!", sex, "ConfigClass", "Client");
            }
            return config;
        }


        /// <summary>
        /// 保存配置文件
        /// </summary>
        /// <param name="strPath"></param>
        /// <param name="config"></param>
        public void WriteUserConfig(string strPath, UserConfig config)
        {
            MemoryStream ms = new MemoryStream();

            BinaryFormatter formatter = new BinaryFormatter();
            // 将配置信息 序列化 并存入内存流中
            formatter.Serialize(ms, config);
            try
            {
                using (FileStream fs = new FileStream(strPath,FileMode.Create,FileAccess.Write)) // 使用UTF8编码格式 覆写已存在的文件
                {
                    byte[] buffer = ms.ToArray();
                    fs.Write(buffer, 0, buffer.GetLength(0));
                    fs.Close();
                }
            }
            catch (IOException ioex)
            {
                throw new MyException("保存配置信息失败", ioex, "ConfigClass", "Client");
            }
        }

    }


返回导读目录,阅读更多随笔



分割线,以下为博客签名:

软件臭虫情未了
  • 编码一分钟
  • 测试十年功


随笔如有错误或不恰当之处、为希望不误导他人,望大侠们给予批评指正。

原文地址:https://www.cnblogs.com/08shiyan/p/1856948.html