2
Answers

csv to datatable sudden error

Daniel Koh

Daniel Koh

7y
241
1
  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)