如何将字典写入计算机并通过不同的方法阅读?

时间:2018-05-27 05:05:22

标签: c#

你能告诉我为什么它不起作用吗?我收到一个错误。我尝试使用你的方法,但它似乎不起作用。

public void OnSignOut(int pin)
    {
        if (this.pin == pin && this.SignIn == true)
        {

            stopwatch.Stop();
            double elasped = stopwatch.Elapsed.TotalSeconds;
            stopwatch.Reset();
            this.total += elasped;
            MessageBox.Show("You have worked for " + elasped + " seconds." + " You have worked for " + this.total + " seconds in total.");
            this.SignIn = false;
            this.end = Convert.ToString(DateTime.Now);
            this.log.Add(this.name + " worked for " + elasped + " seconds." + "\r\n" + "Total Time: " + this.total + " seconds" + "\r\n" + "Log in: " + this.start + "   Log out: " + this.end + "\r\n\r\n\r\n");
            this.logbook.Add(DateTime.Now, elasped);
            json = JsonConvert.SerializeObject(this.logbook);
            System.IO.File.WriteAllText(@"D:\path.json", json);

        }

    }
    public double AddUp_Hours(DateTime start_date, DateTime end_date)
    {
    System.IO.File.ReadAllText(@"D:\path.json");
    this.logbook = JsonConvert.DeserializeObject<Dictionary< DateTime, double> > (json);
        DateTime first = start_date;
        DateTime second = end_date;
        double sums = this.logbook.Where(x => x.Key > first && x.Key < second)
              .Sum(x => x.Value);
        return sums;

1 个答案:

答案 0 :(得分:1)

根据您对可扩展性,功能,安全性等的需求,您有多种选择:

  • 使用app-settings作为键值存储:如果您只有非常少的数据,则不附带任何附加条件
  • 将您的数据序列化为XML / JSON / Binary:如果您有更多数据和值数据可移植性
  • 使用像SQLite这样的轻量级基于文件的数据库存储:如果你有相当多的数据,需要做一些基本的报告等。
  • 如果您有大量数据,打算进行报告,负载平衡,复制等等,请使用完整的数据库。

假设您正在寻找一种小规模,低条形的数据存储解决方案:尝试序列化到JSON开始

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace Dict2JsonSO
{
    class Program
    {
        static void Main(string[] args)
        {

            Dictionary<DateTime, int> dict = new Dictionary<DateTime, int>();
            dict.Add(DateTime.Now, 100);
            dict.Add(DateTime.Now.AddSeconds(10), 10);

            //save
            string json = JsonConvert.SerializeObject(dict);
            System.IO.File.WriteAllText(@"D:\path.txt", json);

            //load
            string loadedJson = System.IO.File.ReadAllText(@"D:\path.txt");
            Dictionary<DateTime, int> loaded = JsonConvert.DeserializeObject<Dictionary<DateTime, int>>(loadedJson);
        }
    }
}

PS:这需要Newtonsoft.Json。通过NuGet安装它。