Reputation: 212
I want to read CSV to array, but the csv cointaned newline inside the cell.
CSV ( csvdata )
Title,Description,Tags,Category,Private,Images MyGreatTitle1,"After this line is blankline Text after blankline",techno,Tech,FALSE,C:\blogpostimg\img1.jpg MyGreatTitle2,"After this line is blankline Text after blankline",techno,Tech,FALSE,C:\blogpostimg\img2.jpg MyGreatTitle3,"After this line is blankline Text after blankline",techno,Tech,FALSE,C:\blogpostimg\img3.jpg MyGreatTitle4,"After this line is blankline Text after blankline",techno,Tech,FALSE,C:\blogpostimg\img4.jpg MyGreatTitle5,"After this line is blankline Text after blankline",techno,Tech,FALSE,C:\blogpostimg\img5.jpg MyGreatTitle6,"After this line is blankline Text after blankline",techno,Tech,FALSE,C:\blogpostimg\img6.jpg
I use this code :
string dir = AppDomain.CurrentDomain.BaseDirectory + @"blogpost";
string[] allLines = File.ReadAllLines(dir + "csvdatabase.csv");
How to read csv line by line but not inside cell?
Upvotes: 1
Views: 3474
Reputation: 12215
As cirrus said, you should probably use a dedicated CSV library, but if you want to do it yourself (or understand how to do it), here is a quickly written CSV parser to give you an idea. It does not handle the full CSV standard, only your specific requirements!
public class CsvParser
{
private readonly List<List<string>> entries = new List<List<string>>();
private string currentEntry = "";
private bool insideQuotation;
/// <summary>
/// Returns all scanned entries.
/// Outer IEnumerable = rows,
/// inner IEnumerable = columns of the corresponding row.
/// </summary>
public IEnumerable<IEnumerable<string>> Entries
{
get { return entries; }
}
public void ScanNextLine(string line)
{
// At the beginning of the line
if (!insideQuotation)
{
entries.Add(new List<string>());
}
// The characters of the line
foreach (char c in line)
{
if (insideQuotation)
{
if (c == '"')
{
insideQuotation = false;
}
else
{
currentEntry += c;
}
}
else if (c == ',')
{
entries[entries.Count - 1].Add(currentEntry);
currentEntry = "";
}
else if (c == '"')
{
insideQuotation = true;
}
else
{
currentEntry += c;
}
}
// At the end of the line
if (!insideQuotation)
{
entries[entries.Count - 1].Add(currentEntry);
currentEntry = "";
}
else
{
currentEntry += "\n";
}
}
}
internal class Program
{
private static void Main(string[] args)
{
string dir = AppDomain.CurrentDomain.BaseDirectory + @"blogpost";
string[] allLines = File.ReadAllLines(dir + "csvdatabase.csv");
CsvParser parser = new CsvParser();
foreach (string line in allLines )
{
parser.ScanNextLine(line);
}
}
}
Upvotes: 2