How to skip first line while reading csv using streamreader

后端 未结 5 1101
自闭症患者
自闭症患者 2020-12-14 01:21

I have my following code to read values from csv file and do some processing. I would like to skip the first row of the input csv file as it contains header text but I\'d wa

相关标签:
5条回答
  • 2020-12-14 01:50

    I recommend, to use technique to handle such situation,

                    int row = 0;
                    using (StreamReader sr = new StreamReader(filePath))
    
                    {
                       While(reader.Read()) //Each row of the file
                        {
                            row++;
                            if(row==1)
                            {
                                continue;
                            }
                   }
    ... code..
    }
    
    0 讨论(0)
  • 2020-12-14 02:02

    Just read it first before you get into the loop. I'd do this:

    using (StreamReader sr = new StreamReader(filePath))
    {
        string headerLine = sr.ReadLine();
        string line;
        while ((line = sr.ReadLine()) != null)
        {
             ...
        }
    }
    

    (I don't like using Peek, personally.)

    Then when you write out the output, start with headerLine.

    0 讨论(0)
  • 2020-12-14 02:06

    Something like this:

    bool isFirst=true;
    using (StreamReader sr = new StreamReader(filePath))
    {
        while (sr.Peek() != -1)
        {
            if(isFirst)
            {
                isFirst=false;
                continue;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-14 02:10

    Just read the first line and do nothing with it...

    List<string> values = new List<string>();
    using (StreamReader sr = new StreamReader(filePath))
    {
        sr.ReadLine();
        while (sr.Peek() != -1)
        {
            string line = sr.ReadLine();
            List<string> lineValues = line.Split(',').ToList();
    
            //***//
        }
    }
    
    0 讨论(0)
  • 2020-12-14 02:12

    You could read the first line before your while loop and store it, or you could use a counter / boolean field to check where in the file you are.

    0 讨论(0)
提交回复
热议问题