示例#1
0
        static void Main(string[] args)
        {
            var filePath = "Employee.txt";

            //OLD WAY: using employee class to store employee info as well as perform read/write and date conversion operations
            EmployeeOld empOld = new EmployeeOld
            {
                Id          = 1001,
                Name        = "John",
                DateOfBirth = new DateTime(1985, 7, 22)
            };

            empOld.Save(empOld, filePath);
            EmployeeOld recordOld = empOld.Load(1001, filePath);



            //BETTER WAY: with Single Responsibility (delegating read/write and date conversion to separate classes)
            EmployeeNew empNew = new EmployeeNew
            {
                Id          = 1002,
                Name        = "Becky",
                DateOfBirth = new DateTime(1987, 2, 27)
            };

            Persistence.Save(empNew, filePath);
            EmployeeNew recordNew = Persistence.Load(1002, filePath);

            Console.ReadKey();
        }
示例#2
0
        public EmployeeOld Load(int id, string filePath)
        {
            EmployeeOld emp         = null;
            var         requestedId = id.ToString();

            if (File.Exists(filePath))
            {
                List <string> rows = File.ReadLines(filePath).ToList();
                foreach (var row in rows)
                {
                    var array = row.Split(',');
                    if (array[0] == requestedId)
                    {
                        int      empId = Convert.ToInt32(array[0]);
                        string   name  = array[1];
                        DateTime dob   = ToDateTime(array[2]);
                        emp = new EmployeeOld
                        {
                            Id          = empId,
                            Name        = name,
                            DateOfBirth = dob
                        };
                        break;
                    }
                }
            }
            return(emp);
        }
示例#3
0
        public void Save(EmployeeOld employee, string filePath)
        {
            string line = string.Join(",", employee.Id, employee.Name, ToDateString(employee.DateOfBirth));

            using (StreamWriter sw = File.AppendText(filePath))
            {
                sw.WriteLine(line);
            }
        }