50 lines
1.7 KiB
C#
50 lines
1.7 KiB
C#
|
|
#nullable enable
|
||
|
|
using System.Collections.Generic;
|
||
|
|
using System.Text;
|
||
|
|
|
||
|
|
namespace ReminderOrganizer.Core
|
||
|
|
{
|
||
|
|
/// <summary>Minimal CSV for ';'-separated files with "quoted" fields (quotes doubled, newlines allowed).</summary>
|
||
|
|
public static class Csv
|
||
|
|
{
|
||
|
|
public const char Separator = ';';
|
||
|
|
|
||
|
|
public static string Escape(string? value)
|
||
|
|
{
|
||
|
|
if (string.IsNullOrEmpty(value)) return "";
|
||
|
|
if (value.IndexOfAny(new[] { Separator, '"', '\n', '\r' }) >= 0)
|
||
|
|
return "\"" + value.Replace("\"", "\"\"") + "\"";
|
||
|
|
return value;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static List<List<string>> Parse(string text)
|
||
|
|
{
|
||
|
|
var rows = new List<List<string>>();
|
||
|
|
var row = new List<string>();
|
||
|
|
var field = new StringBuilder();
|
||
|
|
bool inQuotes = false;
|
||
|
|
|
||
|
|
for (int i = 0; i < text.Length; i++)
|
||
|
|
{
|
||
|
|
char c = text[i];
|
||
|
|
if (inQuotes)
|
||
|
|
{
|
||
|
|
if (c == '"')
|
||
|
|
{
|
||
|
|
if (i + 1 < text.Length && text[i + 1] == '"') { field.Append('"'); i++; }
|
||
|
|
else inQuotes = false;
|
||
|
|
}
|
||
|
|
else field.Append(c);
|
||
|
|
}
|
||
|
|
else if (c == '"') inQuotes = true;
|
||
|
|
else if (c == Separator) { row.Add(field.ToString()); field.Clear(); }
|
||
|
|
else if (c == '\r') { }
|
||
|
|
else if (c == '\n') { row.Add(field.ToString()); field.Clear(); rows.Add(row); row = new List<string>(); }
|
||
|
|
else field.Append(c);
|
||
|
|
}
|
||
|
|
if (field.Length > 0 || row.Count > 0) { row.Add(field.ToString()); rows.Add(row); }
|
||
|
|
return rows;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|