简体   繁体   中英

c# csv data into array

I try to get the data from a csv file into an array in C#. The Problem is that the lines are not seperated by semicolons like all the other values. This means whil just splitting them all, the last one of one line and the first value from the next line are merged into a single position. How can i split it the same way but account for the, i guess, newline (\\n) in the csv file?

My Idea so far would be something like

    String[] xyz;
    For Loop to iterate over the data
      If semicolon, split to the array
      else if \n(?) split into the array.

I am quite new to programming so i just don´t know how to do this properly and hope you can help me.

to parse CSV there is no better option than Lumenworks framwork. Its not only easy to use but it light weight and performance is world class. You can get library from nuget https://www.nuget.org/packages/LumenWorksCsvReader/

and parse your csv like

    using (CsvReader csv = new CsvReader(new StreamReader(fileStream, Encoding.Default), true))
  {
     foreach (var record in csv)
     {
            //PARSE ROWS ONE BY ONE AND GET COLUMN VALUE BY INDEX
     }
  }

You can use open source libraries for loading csv file. There are number of them FileHelpers, CSVReader and Cinchoo ETL.

Cinchoo ETL has CSVReader. An easy, fast and stream based CSV parser.

foreach (dynamic rec in new ChoCSVReader("test.csv").WithFirstLineHeader())
{
    Console.WriteLine(rec.COMPANY_NAME);
    Console.WriteLine(rec.COMPANY_TYPE);
}

If the file is not too large, you can call File.ReadAllLines() first to get the array of text lines. Then you can split the lines in that array.

string[] lines = File.ReadAllLines("MyFile.txt");
string[] splitted;

foreach(string line in lines)
{
  splitted = line.Split(';');
  ...
}

Or you can use a StreamReader .

using (StreamReader sr = File.OpenText("MyFile.txt")) 
{
  string   line;
  string[] splitted;

  while ((line = sr.ReadLine()) != null) 
  {
    splitted = line.Split(';');
    ...
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM