C# 中 实现 Obj(对象)写入文件,从文件读取到对象(Obj)

C# 中 实现 Obj(对象)写入文件,从文件读取到对象(Obj)

  1. 对象我假设一个类:如下(命名控件自定义)
/// <summary>
    /// 用户操作记录类
    /// </summary>
    [Serializable]
    internal class RecordDetail
    {
        /// <summary>
        /// 用户开锁时间
        /// </summary>
        public string _opendatetime { set; get; } = string.Empty;
        /// <summary>
        /// 用户设置时间
        /// </summary>
        public string _settingdatetime { get; set; } = string.Empty;
        /// <summary>
        /// 用户信息类实例化
        /// </summary>
        public userDetails userDetails = new userDetails();
        /// <summary>
        /// 开锁的方式
        /// </summary>
        public string _userOpenType { get; set; } = string.Empty;
        /// <summary>
        /// 用户设置类型
        /// </summary>
        public string _userSettingType { get; set; } = string.Empty;
        /// <summary>
        /// 用户设置的细节
        /// </summary>
        public string _userSettingDetails { get; set; } = string.Empty;  
    }

    [Serializable]
    internal class userDetails
    {
        /// <summary>
        /// 用户Id
        /// </summary>
        public string _useId { get; set; } = string.Empty;
        /// <summary>
        /// 用户姓名
        /// </summary>
        public string _useName { get; set; } = string.Empty;
        /// <summary>
        /// 用户职位
        /// </summary>
        public string _userjob { get; set; } = string.Empty;
        /// <summary>
        /// 用户权限级别
        /// </summary>
        public int _uselevel { get; set; } = 0;
        /// <summary>
        /// 用户授权时间
        /// </summary>
        public string _aollowTime { get; set; } = string.Empty;       
    }

    /// <summary>
    /// 报警操作记录类
    /// </summary>
    [Serializable]
    internal class WarningRecordDetails
    {
        /// <summary>
        /// 报警的时间
        /// </summary>
        public string _warningdatetime { get; set; } = string.Empty;
        /// <summary>
        /// 报警的类型
        /// </summary>
        public string _warningType { get; set; } = string.Empty;
        /// <summary>
        /// 报警的状态
        /// </summary>
        public string _warningStatus { get; set; } = string.Empty;
    }

    /// <summary>
    /// 全局集合类
    /// </summary>
    [Serializable]
    internal class RecordGolable
    {
        /// <summary>
        /// 用户集合
        /// </summary>
        public List<RecordDetail> _recordDetailList = new List<RecordDetail>();
        /// <summary>
        /// 报警集合
        /// </summary>
        public List<WarningRecord> _warningRecordList = new List<WarningRecord>();
        /// <summary>
        /// 用户信息字段,全局变量,方便查询
        /// </summary>
        public Dictionary<string, List<RecordDetail>> _dicRecordDetail = new Dictionary<string, List<RecordDetail>>();
        /// <summary>
        /// 抱紧信息字典,全局变量,方便查询
        /// </summary>
        public Dictionary<string, List<WarningRecord>> _dicWarningRecord = new Dictionary<string, List<WarningRecord>>();
    }
  1. 写实现方法:如下
    2.1 将对象写入文件
/// <summary>
        /// 往文件中写数据
        /// </summary>
        /// <param name="recordDetail"></param>
        /// <param name="warningRecord"></param>
        /// <param name="wrType"></param>
        public void WriteData(RecordDetail recordDetail, WarningRecordDetails warningRecord , string wrType = "")
        {
            lock (this)
            {
                try
                {
                    //创建文件夹
                    pReadByte = new byte[3000];
                    string dataDir = baseDir + path;
                    if (!Directory.Exists(dataDir))// 目录不存在,新建目录
                    {
                        Directory.CreateDirectory(dataDir);                        
                    }
                    if (wrType == "record")
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            IFormatter bf = new BinaryFormatter();
                            bf.Serialize(ms, recordDetail);
                            pReadByte = ms.GetBuffer();
                        }
                    }
                    else if (wrType == "warning")
                    {
                        byte[] pReadByte;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            IFormatter bf = new BinaryFormatter();
                            bf.Serialize(ms, warningRecord);
                            pReadByte = ms.GetBuffer();
                        }
                    }
                    else
                    {
                        MessageBox.Show(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  记录信息保存有误!", "错误!");
                        return;
                    }
                    //将二进制写入文件
                    string str = string.Empty;
                    for (int i = 0; i < pReadByte.Length; i++)
                    {
                        str += pReadByte[i].ToString("X2");
                    }
                    fs = new FileStream(dataDir + "\\" + userfile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                    fs.Seek(0, System.IO.SeekOrigin.End);
                    //文件节流点
                    sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                    sw.WriteLine(str);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception" + ex.Message);
                    return;
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Close();
                        sw = null;
                    }
                    if (fs != null)
                    {
                        fs.Close();
                        fs = null;
                    }                    
                }
            }
        }
  1. 读实现方法:如下
    2.1 将文件读入对象
public RecordGolable ReadDataToMemory(string readtype = "")
        {
            RecordGolable recordGolable = new RecordGolable();
            RecordDetail recordDetail = new RecordDetail();
            BinaryFormatter bf = new BinaryFormatter();
            try
            {
                if(readtype == "record")
                {
                    //获取用户记录信息到内存字典中
                    string dataDir = baseDir + path;
                    fs = new FileStream(dataDir + "\\" + userfile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                    StreamReader read = new StreamReader(fs);
                    //循环读取每一行
                    string strReadline = string.Empty;
                    while ((strReadline = read.ReadLine()) != null)
                    {
                        //对每一行数据做反序列化处理
                        if (strReadline.Length % 2 != 0)
                        {
                            strReadline = "0" + strReadline;
                        }
                        byte[] binReadline = new byte[strReadline.Length / 2];
                        for (int i = 0; i < binReadline.Length; i++)
                        {
                            string b = strReadline.Substring(i * 2, 2);
                            binReadline[i] = Convert.ToByte(b, 16);
                        }
                        using (MemoryStream ms = new MemoryStream(binReadline))
                        {
                            IFormatter iFormatter = new BinaryFormatter();
                            recordDetail = (RecordDetail)iFormatter.Deserialize(ms);
                        }
                        recordGolable._recordDetailList.Add(recordDetail);
                    }                    
                }
                else if(readtype == "warning")
                {
                    //获取用户记录信息到内存字典中
                    string dataDir = baseDir + path;
                    fs = new FileStream(dataDir + "\\" + userfile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                    StreamReader read = new StreamReader(fs);
                    //循环读取每一行
                    string strReadline = string.Empty;
                    while ((strReadline = read.ReadLine()) != null)
                    {
                        //对每一行数据做反序列化处理
                        if (strReadline.Length % 2 != 0)
                        {
                            strReadline = "0" + strReadline;
                        }
                        byte[] binReadline = new byte[strReadline.Length / 2];
                        for (int i = 0; i < binReadline.Length; i++)
                        {
                            string b = strReadline.Substring(i * 2, 2);
                            binReadline[i] = Convert.ToByte(b, 16);
                        }
                        using (MemoryStream ms = new MemoryStream(binReadline))
                        {
                            IFormatter iFormatter = new BinaryFormatter();
                            recordDetail = (RecordDetail)iFormatter.Deserialize(ms);
                        }
                        recordGolable._recordDetailList.Add(recordDetail);
                    }
                }
                recordGolable._dicRecordDetail = new Dictionary<string, List<RecordDetail>>();
                recordGolable._dicRecordDetail.Add(recordDetail.userDetails._useId, recordGolable._recordDetailList);
                return recordGolable;
            }
            catch(Exception ex)
            {
                RecordLog.GetInstance().WriteLog(Level.Error, "Write RecordData Exception: "+ ex.Message);
                return recordGolable;
            }
            finally
            {                
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }                
            }
        }

方法的实现主要是对数据流的操作,其他没什么问题

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值