反序列化出现异常: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");
            }
        }

    }
posted @ 2010-10-20 18:39  把爱延续  阅读(5677)  评论(0编辑  收藏  举报