I’m reading data from a file that I need to be put into my array of objects (myEmployees). I believe my code is correct until the end of this example, but I am not sure how to read the data from the file, split it, and then put it correctly into my array of class objects.
//declare an array of employees
Employee[] myEmployees = new Employee[10];
//declare other variables
string inputLine;
string EmpName;
int EmpNum;
double EmpWage;
double EmpHours;
string EmpAdd;
//declare filepath
string environment = System.Environment.GetFolderPath
(System.Environment.SpecialFolder.Personal) + "\\";
//get input
Console.Write("\nEnter a file name in My Documents: ");
string input = Console.ReadLine();
string path = environment + input;
Console.WriteLine("Opening the file...");
//read file
StreamReader myFile = new StreamReader(path);
inputLine = (myFile.ReadLine());
So I am reading data from a file that is structured like:
Employee Number
Employee Name
Employee Address
Employee wage Employee Hours
I need to read data from this file and parse it into the array of Employees that I’ve created. Here is the class data for class Employee:
public void Employeeconst ()
{
employeeNum = 0;
name = "";
address = "";
wage = 0.0;
hours = 0.0;
}
public void SetEmployeeNum(int a)
{
employeeNum = a;
}
public void SetName(string a)
{
name = a;
}
public void SetAddress(string a)
{
address = a;
}
public void SetWage(double a)
{
wage = a;
}
public void SetHours(double a)
{
hours = a;
}
public int GetEmployeeNum()
{
return employeeNum;
}
public string GetName()
{
return name;
}
public string GetAddress()
{
return address;
}
public double GetWage()
{
return wage;
}
public double GetHours()
{
return hours;
}
Firstly, I would suggest to redesign your Employee class using properties, which is more readable and better follows principles of object oriented programming:
Also consider wrapping StreamReader in ‘using‘ keyword, which ensures that file will be closed correctly. The rest of program is easy, just read your file line by line until end of file. Parse each line to desired type and set value to Employee object:
I did not include eny error checking in my sample code, so it is up to you to do it.