Link to home
Start Free TrialLog in
Avatar of josephdaviskcrm
josephdaviskcrmFlag for United States of America

asked on

C# String.split method on a .csv file

I've got the attached .csv file.  Each record is separated by returns, and the fields in each record are separated by commas.  I've already got the entire contents of the file read into my application.  I need to use the string.split method on it to separate the records into different array elements.  So I need to split the file up by the return character that exists between records.  I've tried using .split('\n'), but that doesn't seem to be working.  Any ideas how I can express that character in my code?

I have the file uploaded as a .txt file, but it is actually a .csv by default.
clearcheckbook.txt
Avatar of numberkruncher
numberkruncher
Flag of United Kingdom of Great Britain and Northern Ireland image

The following works for me:

            string filePath = @"C:\Downloads\clearcheckbook.csv";
 
            try
            {
                StreamReader reader = new StreamReader(filePath);
                string csvData = reader.ReadToEnd();
 
                string[] rows = csvData.Split('\n');
 
                string[][] data = new string[rows.Length][];
                int ri = 0;
                foreach (string row in rows)
                    data[ri++] = row.Split(',');
 
                // Get row 3 and column 2 from data.
                string[] row3 = data[2];
                string row3_col2 = row3[1];
            }
            catch (Exception)
            {
                // An error has occurred!
            }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of numberkruncher
numberkruncher
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial