如何将字典写入本地并多方法读取?及C#代码报错排查请求
字典的本地写入与读取方法(C#)
在C#中,我们常用几种方法来将字典持久化到本地并读取回来,以下是最实用的几种方案:
1. 使用JSON序列化(Newtonsoft.Json)
这是最常用的方式,JSON格式可读性强、跨平台友好,适合大多数场景。
写入字典
using Newtonsoft.Json; using System.IO; // 定义目标字典 Dictionary<DateTime, double> logbook = new Dictionary<DateTime, double>(); logbook.Add(DateTime.Now, 120.5); // 序列化并写入本地文件 string jsonContent = JsonConvert.SerializeObject(logbook); File.WriteAllText(@"D:\path.json", jsonContent);
读取字典
using Newtonsoft.Json; using System.IO; // 读取文件内容并反序列化为字典 string jsonContent = File.ReadAllText(@"D:\path.json"); Dictionary<DateTime, double> logbook = JsonConvert.DeserializeObject<Dictionary<DateTime, double>>(jsonContent);
2. 二进制序列化
适合对性能要求高、不需要可读格式的场景,注意如果自定义类作为字典的Key/Value,需要标记类为[Serializable]。
写入字典
using System.IO; using System.Runtime.Serialization.Formatters.Binary; // 示例字典 Dictionary<int, string> workLog = new Dictionary<int, string>(); workLog.Add(1, "完成任务A"); // 二进制序列化写入 using (FileStream fs = new FileStream(@"D:\workLog.bin", FileMode.Create)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, workLog); }
读取字典
using System.IO; using System.Runtime.Serialization.Formatters.Binary; Dictionary<int, string> workLog; using (FileStream fs = new FileStream(@"D:\workLog.bin", FileMode.Open)) { BinaryFormatter formatter = new BinaryFormatter(); workLog = (Dictionary<int, string>)formatter.Deserialize(fs); }
3. XML序列化
适合需要XML格式的场景,注意.NET原生不支持直接序列化Dictionary,需要包装成可序列化的自定义类:
写入字典
using System.Xml.Serialization; using System.IO; // 自定义可序列化字典类 [XmlRoot("Dictionary")] public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable { // 实现IXmlSerializable接口的标准方法(可网上搜索完整实现) public System.Xml.Schema.XmlSchema GetSchema() => null; public void ReadXml(System.Xml.XmlReader reader) { /* 实现读取逻辑 */ } public void WriteXml(System.Xml.XmlWriter writer) { /* 实现写入逻辑 */ } } // 使用示例 SerializableDictionary<DateTime, double> serialLog = new SerializableDictionary<DateTime, double>(); serialLog.Add(DateTime.Now, 90.0); XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<DateTime, double>)); using (TextWriter writer = new StreamWriter(@"D:\log.xml")) { serializer.Serialize(writer, serialLog); }
读取字典
using System.Xml.Serialization; using System.IO; XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<DateTime, double>)); using (TextReader reader = new StreamReader(@"D:\log.xml")) { SerializableDictionary<DateTime, double> serialLog = (SerializableDictionary<DateTime, double>)serializer.Deserialize(reader); }
你的代码错误排查
看了你提供的代码,有几个明显的问题导致无法运行:
1. AddUp_Hours方法未将文件内容赋值给json变量
你调用了System.IO.File.ReadAllText(@"D:\path.json");但没有把返回的字符串赋值给json变量,后续直接用JsonConvert.DeserializeObject时,json可能是旧值甚至未初始化,会导致反序列化失败。正确写法:
json = System.IO.File.ReadAllText(@"D:\path.json"); // 必须添加赋值操作 this.logbook = JsonConvert.DeserializeObject<Dictionary<DateTime, double>>(json);
2. 变量拼写错误:elasped → elapsed
你在代码中多次把elapsed(表示已流逝的)拼写成了elasped,比如double elasped = stopwatch.Elapsed.TotalSeconds;,这个拼写错误会直接导致编译失败,编译器无法识别未定义的变量。
3. AddUp_Hours方法缺少闭合大括号
你的代码最后只到return sums;,但没有添加}来闭合AddUp_Hours方法,这是语法错误,编译器会提示代码结构不完整。
4. 潜在问题:DateTime作为字典Key的序列化兼容性
虽然Newtonsoft.Json可以处理DateTime作为字典Key,但如果后续反序列化出现时间格式解析问题,可以指定序列化格式来避免:
JsonSerializerSettings settings = new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss" }; json = JsonConvert.SerializeObject(this.logbook, settings);
反序列化时也使用相同的设置即可。
修复以上问题后,你的代码应该就能正常运行了。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

