简体   繁体   中英

how read *.csv file in string array

try to realize reading csv file with some structured data (this file used for my programm reminder - data in file structured with next way: date , name, time from, time till, description). Currently i want to read all data from file and put it in some string array, where each element - 1 line from file. what was done

write some code, that create stream for reading and opening file. But currently i can only read one line. or all file in one line. How to know, how many lines in file exist? or how to read all lines in file in array, where eaach element - one line from file.

Code

    FileStream fs = new FileStream(FilePath, FileMode.Open,
               FileAccess.Read, FileShare.None);
        StreamReader sr = new StreamReader(fs);

        string lines = sr.ReadLine();
       //temp veiw result
        viewTextBox.Text = lines; //read only one first line in file
        sr.Close();

or try to read all lines

        string []line = File.ReadAllLines(FilePath); //read all lines in File
       //temp check
        for (int i=0; i<line.Length;i++){
            viewTextBox.Text += line[i]; // in this case all data stored in one lines
        }

i need this array with data, because next action - search some data in this array and show it in form.

Instead of re-inventing the wheel, I'd rather use a well know and tested library:

"CSV File Parser C# classes for reading and writing CSV files. Support for multi-line fields, custom delimiter and quote characters, options for how empty lines are handled. - Designed to behave much in the way Excel handles CSV files. - Support for multi-line fields. - Ability to customize how empty lines are handled. - Ability to customize delimiter and quote characters."

http://csvfile.codeplex.com/

If you just want to see a simple solution to how you could do it:

IEnumerable<string[]> lineFields = File.ReadAllLines(FilePath).Select(line => line.Split(','));

So then you can access columns by index:

string cellValue = lineFields[lineIndex][columnIndex];

This won't deal with csv files which employ quotes to allow commas within data, for that you'll need to write a routine for splitting quoted strings.

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