-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCsvParser.cs
More file actions
72 lines (65 loc) · 2.52 KB
/
CsvParser.cs
File metadata and controls
72 lines (65 loc) · 2.52 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
/* In the name of God, the Merciful, the Compassionate */
using System.Collections.Generic;
namespace SQLTriage.Data
{
/// <summary>
/// Shared CSV/DSV parsing utilities used by DiagnosticsRoadmap, VulnerabilityAssessment, and tests.
/// </summary>
public static class CsvParser
{
/// <summary>
/// Detects the field delimiter from the header line.
/// Tilde-delimited (sqlmagic) files are detected first; otherwise comma is assumed.
/// </summary>
public static char DetectDelimiter(string headerLine)
=> headerLine.Contains('~') ? '~' : ',';
/// <summary>
/// Parses a single line of a CSV or DSV file into a list of field values.
/// Handles RFC 4180 quoting (comma-delimited) and plain tilde-delimited files.
/// </summary>
public static List<string> ParseLine(string line, char delimiter = ',')
{
var result = new List<string>();
if (delimiter != ',')
{
// Non-comma files (e.g. tilde-delimited sqlmagic) are plain-split;
// strip any stray quotes literally since SQL Server raw output has none.
foreach (var part in line.Split(delimiter))
result.Add(part.Trim().Trim('"').Trim('\''));
return result;
}
int i = 0;
while (i < line.Length)
{
if (line[i] == '"')
{
// Quoted field
i++;
var sb = new System.Text.StringBuilder();
while (i < line.Length)
{
if (line[i] == '"' && i + 1 < line.Length && line[i + 1] == '"')
{
sb.Append('"');
i += 2;
}
else if (line[i] == '"') { i++; break; }
else sb.Append(line[i++]);
}
result.Add(sb.ToString());
}
else
{
int start = i;
while (i < line.Length && line[i] != ',') i++;
result.Add(line[start..i]);
}
if (i < line.Length && line[i] == ',') i++;
}
// A trailing comma means one more empty field
if (line.Length > 0 && line[^1] == ',')
result.Add("");
return result;
}
}
}