Ejemplo n.º 1
0
        // open menu selected
        private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // let the user pick the file to open

            OpenFileDialog ofd = new OpenFileDialog();

            // get the file path
            ofd.Title       = "Select a Contact List";
            ofd.Filter      = "Text Files|*.txt|All Files|*.*";
            ofd.FilterIndex = 1;

            ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            // check dialog result
            DialogResult result = ofd.ShowDialog();

            if (result != DialogResult.OK)
            {
                return;
            }

            // create a new object
            UniversityPeople p = null;

            // save the file path
            Filepath = ofd.FileName;

            try
            {
                StreamReader input = new StreamReader(ofd.FileName);

                while (!input.EndOfStream)
                {
                    string peopleType = input.ReadLine();
                    switch (peopleType)
                    {
                    case "Faculty":
                        p = new Faculty(input.ReadLine());      // create a new faculty
                        break;

                    case "Student":
                        p = new Student(input.ReadLine());     // create a new student
                        break;

                    default:
                        MessageBox.Show("Unknown product in the file");
                        p = null;
                        break;
                    }

                    // add the new object to people list and list box
                    if (p != null)
                    {
                        peopleList.Add(p);
                        allContactListBox.Items.Add(p.ToFormattedString());
                    }
                }

                // close the file
                input.Close();
            }
            catch (Exception excp)
            {
                MessageBox.Show($"File did not load. {excp.Message}");
                return;
            }
        }