首页 > 解决方案 > Windows Form c#在同一个表单上读取和写入同一个文件错误?

问题描述

我目前正在尝试完成这个 c# windows 窗体应用程序。我遇到了麻烦。

这是我的表格的图像...

在此处输入图像描述

这个表格的要点是也允许用户输入上面的数据。在后端,它应该找到最低的测试分数,将其从数组中删除,然后当用户单击“保存学生”时,3 行数据(“学生姓名”、5 次测试的平均值和基于字母的成绩平均而言),应该保存到students.txt文件中。

但是,我的问题可以在下面的列表框中看到。我的问题是我正在从“students.txt”文件加载数据(使用预填充的虚拟数据),每次尝试保存学生时都会出错(因为我无法读取和写入同一个文件) 并且程序将停止运行。

单击任何预填充的数据会弹出另一个表单,其中数据加载到标签中,效果很好...... 在此处输入图像描述

我怎样才能停止这个错误,以便我可以继续我的工作?我也很难理解数据应该在二维数组中的位置。

这是我继续编写代码之前的说明图像。我确信我可以与说明有所不同。

在此处输入图像描述

这是我的主要表单的代码...

namespace Tes3Part2
{
    public partial class Form1 : Form
    {
        private List<PersonEntry> contactList = new List<PersonEntry>();
        private List<string> contactListNames = new List<string>();

        private InfromationForm personInfo = new InfromationForm();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {


            try
            {
                StreamReader inputFile = File.OpenText("students.txt");

                while (!inputFile.EndOfStream)
                {
                    PersonEntry person = new PersonEntry();

                    person.Name = inputFile.ReadLine();
                    person.AverageScore = inputFile.ReadLine();
                    person.LetterGrade = inputFile.ReadLine();

                    contactList.Add(person);
                    contactListNames.Add(person.Name);
                }

                contactListNames.Sort();

                int x = 0;

                while (x < contactListNames.Count)
                {
                    contactList.Insert(x, contactList[SequentialSearch(contactList, contactListNames[x])]);
                    studentsListBox.Items.Add(contactList[x].Name);
                    x++;
                }

            }
            catch
            {
                MessageBox.Show("Welcome.");
            }


        }
        private int SequentialSearch(List<PersonEntry> inputList, string value)
        {
            bool found = false;
            int index = 0;
            int position = -1;

            while (!found && index < inputList.Count)
            {
                if (inputList[index].Name == value)
                {
                    found = true;
                    position = index;
                }

                index++;
            }

            return position;
        }

        private void StudentsListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            personInfo.nameLabel.Text = contactList[studentsListBox.SelectedIndex].Name;
            personInfo.scoreLabel.Text = contactList[studentsListBox.SelectedIndex].AverageScore;
            personInfo.letterLabel.Text = contactList[studentsListBox.SelectedIndex].LetterGrade;
            personInfo.ShowDialog();
        }

        private void Button1_Click(object sender, EventArgs e)
        {

            double test1 = (double.Parse(t1TestBox.Text));
            double test2 = (double.Parse(t1TestBox.Text));
            double test3 = (double.Parse(t1TestBox.Text));
            double test4 = (double.Parse(t1TestBox.Text));
            double test5 = (double.Parse(t1TestBox.Text));
            double average = (test1 * test2 * test3 * test4 * test5) / 5;

            // Declare a StreamWriter variable. 
            StreamWriter outputFile;
            // Create a file and get a StreamWriter object.
            outputFile = File.CreateText("students.txt");
            // Write the info to the file. 
            outputFile.WriteLine(nameTextBox.Text);
            outputFile.WriteLine(average);
            outputFile.WriteLine("F");
            outputFile.Close();

            // Let the user know the name was written. 
            MessageBox.Show("The employee's name was added to the file EmployeePayroll.txt, located" +
                "in the Debug File");

        }

        private void ExitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

这是我的 Person 类的代码

class PersonEntry
    {
        private string _name;
        private string _average;
        private string _letterGrade;

        public PersonEntry()
        {
            _name = "";
            _average = "";
            _letterGrade = "";
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public string AverageScore
        {
            get { return _average; }
            set { _average = value; }
        }

        public string LetterGrade
        {
            get { return _letterGrade; }
            set { _letterGrade = value; }
        }

    }

预先感谢您的所有帮助!

标签: c#visual-studiowindows-forms-designer

解决方案


正如史蒂夫提到的,您在读取和写入文件时使用了 using 语句。

using (StreamReader inputFile = File.OpenText("students.txt"))
        {

            while (!inputFile.EndOfStream)
            {
                PersonEntry person = new PersonEntry();

                person.Name = inputFile.ReadLine();
                person.AverageScore = inputFile.ReadLine();
                person.LetterGrade = inputFile.ReadLine();
            }
        }

        using (StreamWriter outputFile = File.CreateText("students.txt"))
        {
            // Write the info to the file. 
            outputFile.WriteLine(nameTextBox.Text);
            outputFile.WriteLine(average);
            outputFile.WriteLine("F");
            outputFile.Close();

        }

推荐阅读