I am looking to open a comma delimited text file and read its contents into a DataTable. I have already defined a DataTable with columns for home team, away team, home goals and away goals. This corresponds to the structure of the data file that I wish to read from.
The object within C# am I looking for to perform this is the StreamReader object.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\myDataFile.txt");
The data file I wish to read called myDataFile.txt in this example is passed as a parameter in the StreamReader constructor. I am going to read the data file in line by line using a while loop and create a new DataRow too add to my table for each line of data.
The DataRow is created by the method 'NewRow' in the DataTable.
DataRow myRow = importResultsTable.NewRow();
The fields in each DataRow have already been defined in the DataTable as columns so only need populating with the data and then adding to the DataTable.
When all the lines of data have been read the while loop will finish and the data file will be closed, leaving a populated DataTable to perform operations on.
string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test1.txt");
while ((line = file.ReadLine()) != null)
{
string delimiter = ",";
string[] strArray = line.Split(delimiter.ToCharArray());
DataRow myRow = importResultsTable.NewRow();
myRow["homeTeam"] = strArray[0];
myRow["awayTeam"] = strArray[1];
myRow["homeGoals"] = resToInt(strArray[2]);
myRow["awayGoals"] = resToInt(strArray[3]);
importResultsTable.Rows.Add(myRow);
}
file.Close();
ไม่มีความคิดเห็น:
แสดงความคิดเห็น