How to read a CSV file with a cell that has multiple lines using C #

I am trying to read a CSV file that has a cell with multiple lines.

This is what the CSV looks like:
enter image description here

row 1, the Part column has multiple rows.

When I try to read it using the method ReadLine()

:

private void buttonBrowse_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "Excel Worksheets|*.csv";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                String filePathAndName = openFileDialog.FileName;
                StreamReader reader = new StreamReader(filePathAndName);
                String line = reader.ReadLine();
                Console.WriteLine(line);
                do
                {
                     line = reader.ReadLine();
                     Console.WriteLine(line);
                } while (line != null);
            }
        }

      

it splits a cell with multiple lines into the number of lines:

[1]"Time of Day","Process Name","PID","Operation","Path","Result","Detail","Image Path"
[2]"22:52:24.2905182","notepad.exe","4828","Process Start","","SUCCESS","Parent PID: 2484, Command line: ""C:\Windows\system32\notepad.exe"" , Current directory: C:\Users\User\, Environment: 
[3];    =::=::\
[4];    ALLUSERSPROFILE=C:\ProgramData
[5];    APPDATA=C:\Users\User\AppData\Roaming
[6];    asl.log=Destination=file
[7];    CommonProgramFiles=C:\Program Files\Common Files
...

"22:52:24.2905201","notepad.exe","4828","Thread Create","","SUCCESS","Thread ID: 8008","C:\Windows\system32\notepad.exe"
"22:52:24.2915842","notepad.exe","4828","Load Image","C:\Windows\System32\notepad.exe","SUCCESS","Image Base: 0x6f0000, Image Size: 0x30000","C:\Windows\system32\notepad.exe"

      

in the above logs, lines 2-7 should be one line.

I want to read it how powershell did it beautifully here using a function import-csv

:
enter image description here

And you can easily retrieve data from a specific cell by its row and column using the command (example):

$csvContent[0] |select -expand Detail

      

Example:
enter image description here

+3


source to share


2 answers


Instead of manually reading in lines, you can use a library like CsvHelper which will remove most of the headache when parsing csv.



+4


source


I know this is not a very good way to do it, but it works in my case:



lineCounter = 0;
while (!reader.EndOfStream)
{
     var line = reader.ReadLine();
     var values = line.Split(',');

     if(values.Length == 1)
     {
        list4[lineCounter-1] += values[0];
     }
     else
     {
          list1.Add(values[0]);
          list2.Add(values[1]);
          list3.Add(values[2]);
          list4.Add(values[3]);
          lineCounter++;
     }

}

      

+1


source







All Articles