12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- /*
- * 由SharpDevelop创建。
- * 用户: 王刚
- * 日期: 2017/3/17
- * 时间: 9:23
- *
- * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
- */
- using System;
- using System.IO;
- using System.Collections.Generic;
- using System.Linq;
- using Newtonsoft.Json.Linq;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
- /// <summary>
- /// 聊天记录类,将记录保存在本地.
- /// </summary>
- [Serializable]
- public class Chatlog
- {
- const int MAX_MSG_COUNT = 500;
- string _uid = "", _friendid = "";
- public Dictionary<int, string> friendschat = new Dictionary<int, string>();
- public Dictionary<int, string> mywords = new Dictionary<int, string>();
- public void FriendSays(int ts, string talk)
- {
- addTalk(friendschat, ts, talk);
- }
- public void MeSay(string talk)
- {
- addTalk(mywords, (int)DateTime.Now.ToUnixTimeStamp(), talk);
- }
- public Chatlog(string uid, string friendid)
- {
- this._uid = uid;
- this._friendid = friendid;
- if (File.Exists(GetFileName()))
- {
- using(var sr=new FileStream(GetFileName(), FileMode.Open)) {
- var bf = new BinaryFormatter();
- var clog = (Chatlog)bf.Deserialize(sr);
- this.friendschat = clog.friendschat;
- this.mywords = clog.mywords;
- }
- }
- }
- /// <summary>
- /// 析构的时候自动保存
- /// </summary>
- ~Chatlog()
- {
- Save();
- }
- public void Save()
- {
- using (var sw = new FileStream(GetFileName(), FileMode.Create))
- {
- new BinaryFormatter().Serialize(sw, this);
- }
- }
- void addTalk(Dictionary<int, string> log, int ts, string talk)
- {
- if (!log.ContainsKey(ts))
- {
- log.Add(ts, talk);
- if (log.Count > MAX_MSG_COUNT)
- {
- log.Remove(log.Keys.First());
- }
- }
- }
- string GetFileName()
- {
- if (!Directory.Exists(UnityHelper.GetUserDataPath() + "/chatlog/"))
- { // 防御
- Directory.CreateDirectory(UnityHelper.GetUserDataPath() + "/chatlog/");
- }
- return UnityHelper.GetUserDataPath() + "/chatlog/" + _uid + "_" + _friendid; // 无后缀名
- }
- }
|