This repository has been archived by the owner on May 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDB.cs
115 lines (102 loc) · 3.53 KB
/
DB.cs
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using NReco.Csv;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace PacketAnalyzer
{
class DB
{
static Dictionary<string, DB> db = new Dictionary<string, DB>();
static Dictionary<string, string> emptyRow = new Dictionary<string, string>();
public static string Root = "";
public static DB Get(string name)
{
if (db.ContainsKey(name))
{
return db[name];
}
var newDB = new DB(name);
db.Add(name, newDB);
return newDB;
}
bool isEmpty = false;
Dictionary<uint, Dictionary<string, string>> rows = new Dictionary<uint, Dictionary<string, string>>();
public DB(string name, string language = "Chinese")
{
if (Root == "")
{
string libPath = Assembly.GetExecutingAssembly().Location;
if (libPath == "")
{
throw new Exception("Failed to locate the library.");
}
Root = Path.GetDirectoryName(libPath);
}
string filePath = Path.Combine(Root, "DB", language, name + ".csv");
try
{
using (var fs = File.OpenRead(filePath))
{
using (var sr = new StreamReader(fs))
{
int lineNum = -1;
var csvReader = new CsvReader(sr, ",");
string[] columnNames = null;
while (csvReader.Read())
{
++lineNum;
switch (lineNum)
{
case 0: // index
continue;
case 1: // column names
columnNames = new string[csvReader.FieldsCount];
for (int i = 0; i < csvReader.FieldsCount; i++)
{
columnNames[i] = csvReader[i];
}
continue;
case 2: // types
continue;
}
var row = new Dictionary<string, string>();
for (int i = 1; i < csvReader.FieldsCount; i++)
{
if (string.IsNullOrEmpty(columnNames[i])) continue;
row.Add(columnNames[i], csvReader[i]);
}
rows.Add(uint.Parse(csvReader[0]), row);
}
}
}
}
catch
{
isEmpty = true;
}
}
public Dictionary<string, string> FindById(uint id)
{
if (!isEmpty && rows.ContainsKey(id))
{
return rows[id];
}
return emptyRow;
}
public string FindById(uint id, string column)
{
var row = FindById(id);
if (row.TryGetValue(column, out var ret))
{
return ret;
}
else
{
return "(unknown)";
}
}
}
}