-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathReadFromCsvFile.cs
More file actions
337 lines (278 loc) · 11.8 KB
/
ReadFromCsvFile.cs
File metadata and controls
337 lines (278 loc) · 11.8 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
* This file is part of the Buildings and Habitats object Model (BHoM)
* Copyright (c) 2015 - 2025, the respective contributors. All rights reserved.
*
* Each contributor holds copyright over their respective contributions.
* The project versioning (Git) records all such contribution source information.
*
*
* The BHoM is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* The BHoM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this code. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/
using BH.oM.Adapters.File;
using BH.oM.Base.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
namespace BH.Engine.Adapters.File
{
public static partial class Compute
{
/***************************************************/
/**** Public Methods ****/
/***************************************************/
[Description("Read a CSV file into a 2D object array, parsing each column using CsvConfig.ColumnDataFormats when provided.")]
[Input("filePath", "Path to the CSV file.")]
[Input("settings", "CSV settings including delimiter, decimal separator, and per-column formats. If null, defaults are used.")]
[Input("active", "Boolean used to trigger the function.")]
public static IEnumerable<IEnumerable<object>> ReadFromCsvFile(string filePath, CsvConfig settings = null, bool active = false)
{
if (!active)
return Array.Empty<IEnumerable<object>>();
if (string.IsNullOrWhiteSpace(filePath))
{
BH.Engine.Base.Compute.RecordError("The file path must not be empty.");
return Array.Empty<IEnumerable<object>>();
}
if (!System.IO.File.Exists(filePath))
{
BH.Engine.Base.Compute.RecordError($"The file `{filePath}` does not exist.");
return Array.Empty<IEnumerable<object>>();
}
if (settings == null)
settings = new CsvConfig();
var delim = settings.Delimiter ?? "\t";
string[] lines;
try
{
lines = System.IO.File.ReadAllLines(filePath);
}
catch (Exception e)
{
BH.Engine.Base.Compute.RecordError($"Error reading file:\n\t{e}");
return Array.Empty<IEnumerable<object>>();
}
if (lines.Length == 0)
return Array.Empty<IEnumerable<object>>();
// 1) Parse lines into raw string rows (CSV rules: quotes + escaped quotes)
var rawRows = new List<string[]>();
for (int i = 0; i < lines.Length; i++)
{
var line = lines[i];
if (string.IsNullOrEmpty(line))
continue;
rawRows.Add(SplitCsvLine(line, delim));
}
if (rawRows.Count == 0)
return Array.Empty<IEnumerable<object>>();
// 2) Normalize columns (pad ragged rows to max width)
int rAll = rawRows.Count;
int c = 0;
for (int i = 0; i < rAll; i++)
if (rawRows[i].Length > c) c = rawRows[i].Length;
if (c == 0)
return Array.Empty<IEnumerable<object>>();
// 3) Decide data start index based on IncludeHeader
var result = new List<List<object>>(rAll);
for (int i = 0; i < rAll; i++)
{
bool isHeader = settings.IncludeHeader && i == 0;
var src = rawRows[i];
var row = new List<object>(c);
for (int j = 0; j < c; j++)
{
string cell = j < src.Length ? src[j] : null;
row.Add(ParseCell(cell, j, settings, isHeader));
}
result.Add(row);
}
return result;
}
/***************************************************/
/**** Private Helpers ****/
/***************************************************/
private static string[] SplitCsvLine(string line, string delimiter)
{
if (string.IsNullOrEmpty(line))
return Array.Empty<string>();
var cells = new List<string>();
var current = new System.Text.StringBuilder();
bool inQuotes = false;
int i = 0;
int n = line.Length;
int dlen = string.IsNullOrEmpty(delimiter) ? 0 : delimiter.Length;
while (i < n)
{
char ch = line[i];
if (ch == '"')
{
if (inQuotes && i + 1 < n && line[i + 1] == '"')
{
current.Append('"'); // Escaped quote
i += 2;
continue;
}
inQuotes = !inQuotes;
i++;
continue;
}
if (!inQuotes && dlen > 0 && i + dlen <= n &&
string.CompareOrdinal(line, i, delimiter, 0, dlen) == 0)
{
cells.Add(current.ToString());
current.Length = 0;
i += dlen;
continue;
}
current.Append(ch);
i++;
}
cells.Add(current.ToString());
return cells.ToArray();
}
/***************************************************/
private static object ParseCell(string raw, int columnIndex, CsvConfig settings, bool isHeader = false)
{
if (string.IsNullOrEmpty(raw))
return null;
if (isHeader)
return raw;
bool hasColumnFormat =
settings.ColumnDataFormats != null &&
columnIndex >= 0 &&
columnIndex < settings.ColumnDataFormats.Count;
if (hasColumnFormat)
{
switch (settings.ColumnDataFormats[columnIndex])
{
case StringType.Boolean:
{
var b = ParseBool(raw, settings);
return b.HasValue ? (object)b.Value : null;
}
case StringType.Numeric:
{
var num = ParseNumeric(raw, settings.DecimalSeparator);
return num.HasValue ? (object)num.Value : null;
}
case StringType.Date:
{
var dt = ParseDate(raw, settings.DateTimeFormat);
if (dt.HasValue) return dt.Value;
// OA serial fallback (Excel serial date)
var serial = ParseNumeric(raw, settings.DecimalSeparator);
if (serial.HasValue)
{
try { return DateTime.FromOADate(serial.Value); }
catch { /* ignore */ }
}
return null;
}
case StringType.Text:
return raw;
}
}
// Try Bool
var bParsed = ParseBool(raw, settings);
if (bParsed.HasValue) return bParsed.Value;
// Try Number
var d = ParseNumeric(raw, settings.DecimalSeparator);
if (d.HasValue) return d.Value;
// Try Date
var when = ParseDate(raw, settings.DateTimeFormat);
if (when.HasValue) return when.Value;
// OA serial fallback
var serial2 = ParseNumeric(raw, settings.DecimalSeparator);
if (serial2.HasValue)
{
try { return DateTime.FromOADate(serial2.Value); }
catch { /* ignore */ }
}
// Text as-is
return raw;
}
/***************************************************/
private static bool? ParseBool(string raw, CsvConfig settings)
{
if (string.Equals(raw, "true", StringComparison.OrdinalIgnoreCase)) return true;
if (string.Equals(raw, "false", StringComparison.OrdinalIgnoreCase)) return false;
if (settings.BooleanAsNumber)
{
if (raw == "1") return true;
if (raw == "0") return false;
}
return null;
}
/***************************************************/
private static double? ParseNumeric(string raw, string decimalSeparator)
{
if (string.IsNullOrEmpty(raw))
return null;
var norm = string.IsNullOrEmpty(decimalSeparator) || decimalSeparator == "."
? raw
: raw.Replace(decimalSeparator, ".");
if (double.TryParse(norm, NumberStyles.Any, CultureInfo.InvariantCulture, out var value))
return value;
return null;
}
/***************************************************/
private static DateTime? ParseDate(string raw, DateFormatOptions option)
{
if (string.IsNullOrEmpty(raw))
return null;
string[] patterns;
switch (option)
{
case DateFormatOptions.ISO8601:
patterns = new[]
{
"o",
"yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-ddTHH:mm:ss.FFFFFFFK",
"yyyy-MM-dd"
};
break;
case DateFormatOptions.US:
patterns = new[]
{
"MM/dd/yyyy",
"M/d/yyyy",
"MM/dd/yy"
};
break;
case DateFormatOptions.EU:
default:
patterns = new[]
{
"dd/MM/yyyy",
"d/M/yyyy",
"dd/MM/yy"
};
break;
}
for (int i = 0; i < patterns.Length; i++)
{
DateTime tmp;
if (DateTime.TryParseExact(raw, patterns[i], CultureInfo.InvariantCulture,
DateTimeStyles.None, out tmp))
return tmp;
}
DateTime any;
if (DateTime.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.None, out any))
return any;
return null;
}
/***************************************************/
}
}