/* * 由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; /// /// 聊天记录类,将记录保存在本地. /// [Serializable] public class Chatlog { const int MAX_MSG_COUNT = 500; string _uid = "", _friendid = ""; public Dictionary friendschat = new Dictionary(); public Dictionary mywords = new Dictionary(); 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; } } } /// /// 析构的时候自动保存 /// ~Chatlog() { Save(); } public void Save() { using (var sw = new FileStream(GetFileName(), FileMode.Create)) { new BinaryFormatter().Serialize(sw, this); } } void addTalk(Dictionary 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; // 无后缀名 } }