Daniel Koh

Daniel Koh

  • 1.8k
  • 60
  • 7.8k

csv to datatable sudden error

Nov 8 2017 9:01 PM
  1. string CSVFilePathName = @"C:\test.csv";    
  2. string[] Lines = File.ReadAllLines(CSVFilePathName);    
  3. string[] Fields;    
  4. Fields = Lines[0].Split(new char[] { ',' });    
  5. int Cols = Fields.GetLength(0);    
  6. DataTable dt = new DataTable();    
  7. //1st row must be column names; force lower case to ensure matching later on.    
  8. for (int i = 0; i < Cols; i++)    
  9.     dt.Columns.Add(Fields[i].ToLower(), typeof(string));    
  10. DataRow Row;    
  11. for (int i = 1; i < Lines.GetLength(0); i++)    
  12. {    
  13.     Fields = Lines[i].Split(new char[] { ',' });    
  14.     Row = dt.NewRow();    
  15.     for (int f = 0; f < Cols; f++)    
  16.         Row[f] = Fields[f];    
  17.     dt.Rows.Add(Row);    
  18. }   
This is the code I have, which was working fine yesterday. However today without any changes made to the code it says:
 
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
 
Any possible solutions?

Answers (2)