-1

I have a CSV file that I need to open in C# as a sequential file. It has to be parsed by the headers.

As of now I have only figured out how to load the data file as a sequential file using C# System.IO library into an ArrayList structure. Each line in the file has to be a separate record. This is it here:

using System;
using System.IO;
using System.Collections;

namespace FileSearch
{
class Class1
{
    static void Main(string[] args)
    {
        StreamReader objReader = new StreamReader("c:\\Users/Sarah/Desktop/IP4Data.csv"); //open file to read
        string sLine = ""; //string variable for data that goes into ArrayList
        ArrayList arrText = new ArrayList();

        while (sLine != null)
        {
            sLine = objReader.ReadLine(); //read file one line at a time
            if (sLine != null) //if empty, it's null
                arrText.Add(sLine);//Add data to Array List
        }
        objReader.Close(); //end loop

        foreach (string sOutput in arrText) //Outputs read data from ArrayList onto screen
            Console.WriteLine(sOutput);
        Console.ReadLine();
    }
}
}

How do I parse the CSV file so it can be searchable in the ArrayList?

AnemonePoppy
  • 51
  • 1
  • 11
  • Have you read how CSV file is built? If yes, have you understood it? If yes, have you started implementing it? –  Oct 29 '14 at 19:52
  • 1
    Any reason you're using `ArrayList` instead of `List<>`? Not that it's invalid, [it's just the old way of doing it](http://stackoverflow.com/a/2309699/1765721). – Jeremy K Oct 29 '14 at 19:55
  • 1
    you'll need to provide a sample of the CSV and describe what you mean by `searchable` – Jonesopolis Oct 29 '14 at 20:04
  • For more complex parsing that `String.Split()` can't handle, I tried using `Regex.Split()` and the pattern `",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"` found in [this Java solution](http://stackoverflow.com/a/15739087/1765721) however it wasn't providing the correct result. Maybe you, or someone else, can fix it up to work in C#. – Jeremy K Oct 29 '14 at 21:14

1 Answers1

1

You can split every line with String.Split method. Like

var fields = sLine.Split(new char[]{','});

if your values are separated by comma

Michael
  • 1,027
  • 10
  • 22
  • What if `,` will be inside field value? Simple spliiting is not enough. –  Oct 29 '14 at 19:59
  • I don't know the way how to use separator symbol inside the field in CSV file. If it is possible the symbol must be escaped somehow i suppose. – Michael Oct 29 '14 at 20:02