title: Trouble with parsing CSV files in C#
body: <p>I'm trying to import a CSV file to my C# site and save it in the database. While doing research I learned about CSV parsing, I've tried to implement this but I've ran into some trouble. Here is a portion of my code so far:</p>
  
  <pre><code>string fileext = Path.GetExtension(fupcsv.PostedFile.FileName);
  
  if (fileext == ".csv")
  {
      string csvPath = Server.MapPath("~/CSVFiles/") + Path.GetFileName(fupcsv.PostedFile.FileName);
  
      fupcsv.SaveAs(csvPath);
  
      // Add Columns to Datatable to bind data  
  
      DataTable dtCSV = new DataTable();
  
      dtCSV.Columns.AddRange(new DataColumn[2] { new DataColumn("ModuleId", typeof(int)), new DataColumn("CourseId", typeof(int))});
  
      // Read all the lines of the text file and close it.  
  
      string[] csvData = File.ReadAllLines(csvPath);
  
      // iterate over each row and Split it to New line.  
  
      foreach (string row in csvData)
      {
  
          // Check for is null or empty row record  
  
          if (!string.IsNullOrEmpty(row))
          {
  
              using (TextFieldParser parser = new TextFieldParser(csvPath))
              {
                  parser.TextFieldType = FieldType.Delimited;
                  parser.SetDelimiters(",");
                  while (!parser.EndOfData)
                  {
                      //Process row
                      string[] fields = parser.ReadFields();
                      int i = 1;
                      foreach (char cell in row)
                      {
                          dtCSV.NewRow()[i] = cell;
                          i++;
                      }
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>I keep getting the error "There is no row at position -1" at " dtCSV.Rows[dtCSV.Rows.Count - 1][i] = cell;"
  Any help would be greatly appreciated, thanks</p>