How to read data that includes datetime from a textfile to a list in C#

  • Thread starter Thread starter Cliff Madz
  • Start date Start date
C

Cliff Madz

Guest
private void SelectCityForm_Load(object sender, EventArgs e)
{

//declaring the file path
string filepath = @"CapturedData.txt";

List<string> lines = File.ReadAllLines(filepath).ToList();

foreach (var line in lines)
{
//Slitting every data values with a comma
string[] entries = line.Split(',');

string format = "dd-MMM-YY h:mm:ss tt";

ForecastingModel forecasting = new ForecastingModel();

forecasting.StrCity = entries[0];
forecasting.DtDate = DateTime.ParseExact(entries[1], format, CultureInfo.InvariantCulture);
forecasting.DtDate = Convert.ToDateTime(entries[1]);
forecasting.MinimumTemp = int.Parse(entries[2]);
forecasting.MaxmumTemp = int.Parse(entries[3]);
forecasting.PrecipitationAmount = int.Parse(entries[4]);
forecasting.HumidityAmount = int.Parse(entries[5]);
forecasting.WindspeedAmount = int.Parse(entries[6]);

myForecastingGlobal.myselectedCites.Add(forecasting);
}

Please help I'm still new to c#. I'm trying to read the following data from a textfile using the above method. the data includes datetime. It gives me this error below only on line 80 - forecasting.DtDate = DateTime.ParseExact(entries[1], format, CultureInfo.InvariantCulture);

This is the runtime error

IndexOutOfRangeException

The data in the text file is as below:

Jhb, 12-Aug-20 1:58:43 PM, 23, 24, 23, 12, 12
Pretoria, 27-Aug-20 1:59:33 PM, 23, 24, 15, 10, 8
Polokwane, 22-Sep-20 2:00:18 PM, 39, 35, 18, 21, 15
Durban, 15-Jul-20 2:01:13 PM, 14, 23, 23, 18, 17

Continue reading...
 
Back
Top