none
Read and Parse a CSV File

    Question

  • I am having a heck of a time getting my code to work.  I can get it to read my CSV file but how do I identify the headers that I need to use in a select after I have it loaded?  I am using Visual Studio 2010 and a newbie at this.  Any prompt help is greatly appreciated. 
    Sunday, March 04, 2012 8:19 PM

Answers

  • Hi, 

    There cant be any identifier, to say this row is header row in csv, every requirement has its own format. If You are thinking in your requirement it is first row is header row, 

    int entriesFound = 0;
                using (var textReader = new StreamReader("fileName"))
                {
                    string line = textReader.ReadLine();
                    int skipCount = 0;
                    while (line != null && skipCount < 1)
                    {
                        line = textReader.ReadLine();
                        
                        skipCount++;
                    }
    
                    while (line != null)
                    {
                        string[] columns = line.Split(_Delimiter);
                        //perform your logic
                        entriesFound++;
                        line = textReader.ReadLine();
                    }
                }

    Hope this helps you...


    If this post answers your question, please click "Mark As Answer". If this post is helpful please click "Mark as Helpful".

    Monday, March 05, 2012 10:11 AM
  • I would recommend just using somebody's existing code.

    http://www.koders.com/csharp/fid881E3E70CC37E480545A0C37C98BC8C208B06723.aspx?s=datatable

    To the left is a little box that lists 4 files "Options.cs" "Parser.cs" "Utils.cs" "Writer.cs"

    This is fairly decent code and it is the basis that I use for my CSV importing/exporting. I only had to make a few modifications to make to fix one or two bugs on more complicated CSV files.

    OOB it should work better than 95% of the CSV parsers that are posted on the internet.

    Monday, March 05, 2012 7:04 PM

All replies

  • With no idea of what you are doing in code and no idea about the layout of your csv I have no idea how to help you.

    Regards David R
    ---------------------------------------------------------------
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.

    Sunday, March 04, 2012 9:27 PM
  •   

    It would be helpful if you post a sample of the csv file showing the lines of data and header lines as well. Also please state how you want to process the fields of the data.

     


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Sunday, March 04, 2012 10:00 PM
  • Hi, 

    There cant be any identifier, to say this row is header row in csv, every requirement has its own format. If You are thinking in your requirement it is first row is header row, 

    int entriesFound = 0;
                using (var textReader = new StreamReader("fileName"))
                {
                    string line = textReader.ReadLine();
                    int skipCount = 0;
                    while (line != null && skipCount < 1)
                    {
                        line = textReader.ReadLine();
                        
                        skipCount++;
                    }
    
                    while (line != null)
                    {
                        string[] columns = line.Split(_Delimiter);
                        //perform your logic
                        entriesFound++;
                        line = textReader.ReadLine();
                    }
                }

    Hope this helps you...


    If this post answers your question, please click "Mark As Answer". If this post is helpful please click "Mark as Helpful".

    Monday, March 05, 2012 10:11 AM
  • Here is some code I was using to do CSV parsing, take a look at it and see if it will help you. It uses the built in OleDbConnection and does the parsing for you:

     OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\;Extended Properties=""Text;HDR=No;FMT=Delimited""");
          OleDbCommand cmd = new OleDbCommand(@"SELECT * FROM d:\temp\combined.csv", cn);
    
          cn.Open();
          string currentValue = string.Empty;
          using (TextWriter writer = new StreamWriter(@"D:\temp\combined3.csv", false))
          {
            using (IDataReader reader = cmd.ExecuteReader())
            {
              while (reader.Read())
              {
                //Process each field here.
              }
            }
          }
    Hope this helps.
    Monday, March 05, 2012 12:57 PM
  •  If I am understanding you right, you want to manipulate the file in code as data. if that is right then you need to import it into a datatable and then you can do what you want. suppose your csv is as follows with an "ID","FirstName","LastName" as the columns

    1,Mickey,Mouse

    2,Minnie,Mouse

    3,Donald,Duck

    Create a datatable and the corresponding columns and then import the csv file directly into the datatable. as I have done below

    private DataTable ReadFile(string FileName)
    {
     DataTable dt = new DataTable();
     dt.Columns.Add("ID", typeof(int));
     dt.Columns.Add("FirstName", typeof(string));
     dt.Columns.Add("LastName", typeof(string));
     String input;
     using (StreamReader sr = new StreamReader(FileName))
     {
      while (sr.Peek() >= 0)
      {
       DataRow dr = dt.NewRow();
       input = sr.ReadLine();
       string[] columns = input.Split(',');
       dr["ID"] = columns[0].ToString();
       dr["FirstName"] = columns[1].ToString();
       dr["LastName"] = columns[2].ToString();
      }
     }
     return dt;
    }

    Now use a method like this one to call the ReadFile Method.

    private void OpenMyfile(string MyfileName)

    {

    DataTable dt = ReadFile(MyfileName)

    // now you can can manipulate the data or use it as a datasource for a grid or combox or anything that uses a Datasource

    // you can do things like

    DataRow[] foundrows = dt.Select("LastName = 'Mouse'");  //this would give you all records where the lastname = Mouse

     }

    Hope this helps


    Richard Trotter


    • Proposed as answer by sax-player Monday, March 05, 2012 6:45 PM
    • Edited by sax-player Monday, March 05, 2012 6:47 PM
    • Unproposed as answer by MarcDModerator Tuesday, March 06, 2012 8:40 PM
    • Proposed as answer by Bhagyesh Desai Tuesday, February 04, 2014 3:41 PM
    Monday, March 05, 2012 6:42 PM
  • I would recommend just using somebody's existing code.

    http://www.koders.com/csharp/fid881E3E70CC37E480545A0C37C98BC8C208B06723.aspx?s=datatable

    To the left is a little box that lists 4 files "Options.cs" "Parser.cs" "Utils.cs" "Writer.cs"

    This is fairly decent code and it is the basis that I use for my CSV importing/exporting. I only had to make a few modifications to make to fix one or two bugs on more complicated CSV files.

    OOB it should work better than 95% of the CSV parsers that are posted on the internet.

    Monday, March 05, 2012 7:04 PM