I am trying to read a *.csv-file.
The *.csv-file consist of two columns separated by semicolon (\";\").
I am able
Still wrong. You need to compensate for "" in quotes. Here is my solution Microsoft style csv.
///
/// Microsoft style csv file. " is the quote character, "" is an escaped quote.
///
///
///
///
///
///
public static List ReadCSVFileMSStyle(string fileName, char sepChar = ',', char quoteChar = '"')
{
List ret = new List();
string[] csvRows = System.IO.File.ReadAllLines(fileName);
foreach (string csvRow in csvRows)
{
bool inQuotes = false;
List fields = new List();
string field = "";
for (int i = 0; i < csvRow.Length; i++)
{
if (inQuotes)
{
// Is it a "" inside quoted area? (escaped litteral quote)
if(i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i+1] == quoteChar)
{
i++;
field += quoteChar;
}
else if(csvRow[i] == quoteChar)
{
inQuotes = false;
}
else
{
field += csvRow[i];
}
}
else // Not in quoted region
{
if (csvRow[i] == quoteChar)
{
inQuotes = true;
}
if (csvRow[i] == sepChar)
{
fields.Add(field);
field = "";
}
else
{
field += csvRow[i];
}
}
}
if (!string.IsNullOrEmpty(field))
{
fields.Add(field);
field = "";
}
ret.Add(fields.ToArray());
}
return ret;
}
}