hxb
2020-09-23 2921da3e4ba99f0df28a172d47daa69e375431bc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
 
 
 
using HDLCloudMonitorSupportCtrlOldUdpGate.Context;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
 
namespace HDLCloudMonitorSupportCtrlOldUdpGate.Logs
{
    public partial class MqttLogHp
    {
        private static Object lockObj = new Object();
 
        public static void Save()
        {
            lock (lockObj)
            {
                ProcessLogDir();
                string currentDataFilePath = $"~/LogDir/{GetCurrentTimeFormatStr()}.txt";
                string content = JsonConvert.SerializeObject(GlobalRecordContext.CtrlRecordDto);
                AppendTextToFile(currentDataFilePath, content, true);
            }
        }
 
 
        public static List<CtrlRecordDto> ReadDataByDateHours(string dateHours)
        {
            var dataList = new List<CtrlRecordDto>();
            
            string currentDataFilePath = MapPath($"~/LogDir/{dateHours}.txt");
            if (File.Exists(currentDataFilePath))
            {
                string[] fileAllLines = File.ReadAllLines(currentDataFilePath);
                foreach (var lineJson in fileAllLines)
                {                    
                    dataList.Add(JsonConvert.DeserializeObject<CtrlRecordDto>(lineJson));
                }              
            }
            return dataList;
        }
 
        private static void ProcessLogDir()
        {
            string logDirPath = MapPath($"~/LogDir");
            if (!Directory.Exists(logDirPath))
            {
                Directory.CreateDirectory(logDirPath);
            }
        }
 
        private static string GetCurrentTimeFormatStr()
        {
            return DateTime.Now.ToString(Consts.DateTimeFormatHoursStr);
        }
 
        private static void AppendTextToFile(string path, string content, bool isAddRn = true)
        {
            path = MapPath(path);
 
            if (isAddRn)
            {
                File.AppendAllText(path, content + "\r\n");
            }
            else
            {
                File.AppendAllText(path, content);
            }
        }
 
        private static string MapPath(string path)
        {
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
            return Path.Combine(baseDirectory, path);   //Path.Combine() 特别适合生成  aa\bb 类型目录
        }
    }
}