Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# CSV line
Hi there,
 
I have to implement a CSV reader and I have managed to implement the standard rules of a CSV file (http://en.wikipedia.org/wiki/Comma-separated_values[^]), except the situation of a line break. I want my class to return the field with the new line feed if the field containing the line break is enclosed in double qoute.
 
Here is the code (please, if possible, can it be kept this way?):
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
 
namespace CSVReader
{
    public class CsvRow : List<string>
    {
        public string LineText { get; set; }
        public CsvRow(List<string> values)
        {
            this.AddRange(values);
        }
        public CsvRow()
        {
 
        }
    }
 
    #region CSV Reader
    public class CsvFileReader : StreamReader
    {
        public CsvFileReader(Stream stream)
            : base(stream)
        {
        }
 
        public CsvFileReader(string filename)
            : base(filename)
        {
        }
 
        /// <summary>
        /// Reads a row of data from a CSV file
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public bool ReadRow(CsvRow row)
        {
            row.LineText = ReadLine();
            if (String.IsNullOrEmpty(row.LineText))
                return false;
 
            int pos = 0;
            int rows = 0;
 
            while (pos < row.LineText.Length)
            {
                string value;
 
                // Special handling for quoted field
                if (row.LineText[pos] == '"')
                {
                    // Skip initial quote
                    pos++;
 
                    // Parse quoted value
                    int start = pos;
                    while (pos < row.LineText.Length)
                    {
                        // Test for quote character
                        if (row.LineText[pos] == '"')
                        {
                            // Found one
                            pos++;
 
                            // If two quotes together, keep one
                            // Otherwise, indicates end of value
                            if (pos >= row.LineText.Length || row.LineText[pos] != '"')
                            {
                                pos--;
                                break;
                            }
                        }
                        pos++;                        
                    }
                    value = row.LineText.Substring(start, pos - start);
                    value = value.Replace("\"\"", "\"");
                }
                else
                {
                    // Parse unquoted value
                    int start = pos;
                    while (pos < row.LineText.Length && row.LineText[pos] != ',')
                        pos++;
                    value = row.LineText.Substring(start, pos - start);
                }
 
                // Add field to list
                if (rows < row.Count)
                    row[rows] = value;
                else
                    row.Add(value);
                rows++;
 
                // Eat up to and including next comma
                while (pos < row.LineText.Length && row.LineText[pos] != ',')
                    pos++;
                if (pos < row.LineText.Length)
                    pos++;
            }
            // Delete any unused items
            while (row.Count > rows)
                row.RemoveAt(rows);
 
            // Return true if any columns read
            return (row.Count > 0);
        }
    }
    #endregion
 
    class Program
    {
        static void Main(string[] args)
        {
            using (CsvFileReader csv = new CsvFileReader("CSV.csv"))
            {
                CsvRow csvRow = new CsvRow();
                int i = 1;
                while (csv.ReadRow(csvRow))
                {
                    Console.Write("LINIA {0}: : ", i);
                    foreach (string sir in csvRow)
                    {
                        Console.Write(sir);
                        Console.Write("\t\t");
                    }
                    Console.WriteLine();
                    i++;
                }
            }
        }
    }
}
 
Posted 28-May-12 4:08am
Comments
Umer Aziz Malik at 28-May-12 9:24am
   
Can you please give an example of what you want to achieve? As in give a sample line that you want to separate as well as the result you want to achieve
Roman Mihai at 28-May-12 9:35am
   
A CSV file has some rules. If i want a field to containt a comma i must enclose it in double quote. If the CSV row is like: Field1, field2, field,3 when I open the CSV file it will have 4 fields. But if I have the CSV row like this: Field1, field2, "field,3" I will have only 3 rows the last one being Field,3. I want the same for the line break. I want to enclose the field containing the line break. The formatting of a CSV can be seen if opened with notepad. So I want my program to verify if the line break is in a quoted field (like "Field CR/LF 3"). Also see the page on the link I have provided, at the bottom of the page
Umer Aziz Malik at 28-May-12 9:36am
   
Are you talking about a line break or a white space? :S
Roman Mihai at 28-May-12 9:45am
   
A line break.
In the CSV file I will have:
 
LastName FirstName School
Middle Name
 
all on the same row and FirstName and MiddleName in the same cell. And the field containing the line break will be enclosed in double quotes.

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

hi
 
refer this link
CSV to data table in c#[^]
  Permalink  
Comments
Roman Mihai at 28-May-12 9:59am
   
I would like to keep it as a C# Console Application for the moment, as I am just testing. After I cover all the cases I would use the data tabel aproach

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web03 | 2.8.1411022.1 | Last Updated 28 May 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100