/// <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");
            }
        }

    }

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-15
  • 2021-12-15
  • 2022-12-23
  • 2021-11-13
  • 2022-02-12
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-06-07
  • 2022-03-02
  • 2022-12-23
  • 2021-10-10
  • 2022-12-23
相关资源
相似解决方案