dmdb/model/CsvFile.cs

96 lines
3.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace dezentrale.model
{
public class CsvFile
{
public List<List<string>> FileContents { get; set; } = new List<List<string>>();
public char FieldSeparator { set; get; } = ',';
public void AdaptDecimalSeparator(string oldSeparator, string newSeparator)
{
foreach(List<string> l in FileContents)
{
for (int i = 0; i < l.Count; i++)
{
l[i] = l[i].Replace(oldSeparator, newSeparator);
}
}
}
public void ReadFile(string fileName)
{
bool quot = false; //current char is in quoted space
bool quotEnd = false; //quoted space ended just before this char (needed to detect "\"\"")
FileContents = new List<List<string>>();
string inputData = File.ReadAllText(fileName).Replace("\r\n","\n").Replace('\r', '\n');
List<string> currentLine = new List<String>();
string currentField = "";
foreach(char c in inputData)
{
if(quot)
{
if(c == '"')
{
quot = false;
quotEnd = true;
continue;
}
}
if (!quot)
{
if(c == '"')
{
quot = true;
if(!quotEnd) continue; //this will add one \" to the string, if the input had \"\"
}
quotEnd = false;
if (c == '\n') //line done
{
currentLine.Add(currentField);
currentField = "";
FileContents.Add(currentLine);
currentLine = new List<String>();
continue;
}
else if (c == FieldSeparator) //field done
{
currentLine.Add(currentField);
currentField = "";
continue;
}
}
currentField += c;
}
currentLine.Add(currentField);
FileContents.Add(currentLine);
}
public void SaveFile(string fileName)
{
StringBuilder sb = new StringBuilder();
for (int l = 0; l < FileContents.Count; l++)
{
List<string> line = FileContents[l];
for (int f = 0; f < line.Count; f++)
{
string s = line[f];
if (s == null) s = "null";
sb.Append("\"" + s.Replace("\"", "\"\"") + "\"");
if (f < line.Count - 1) sb.Append(FieldSeparator);
}
if (l < FileContents.Count - 1) sb.Append('\n');
}
File.WriteAllText(fileName,sb.ToString());
}
}
}