如何从用户输入写入 C# 中的不同文件

How to write to different files in C# from user inputs

我需要将用户输入的学生姓名和学生分数添加到两个不同的文件中。这是我当前的代码。我正在尝试将用户输入添加到数组中,然后将其添加到文件中。它作为一个子程序运行,远离我的主要代码,它不需要 return 任何东西。

    //subroutine to input data and save to a new file 
    public static void SaveToFile()
    {
        BinaryWriter bw;
        string[] studentName;
        int[] studentMark;
        BinaryWriter nameFile;
        BinaryWriter markFile;

        nameFile = new BinaryWriter(new FileStream("studentNames.txt", FileMode.Create));
        markFile = new BinaryWriter(new FileStream("studentMarks.txt", FileMode.Create));
        Console.WriteLine("Enter a student name and a mark or, END to finish: ");
        while (/*The input*/ != "END")
        {
            Console.WriteLine("Enter student name: ");
            studentName = Console.ReadLine();
            Console.WriteLine("Enter mark: ");
            studentMark = Convert.ToInt32(Console.ReadLine());

        }
        bw.Close();
        return;
    }

您要将数据写入二进制还是文本? 你想在每个值之间换行吗?我添加了一个,你可以删除它或将其更改为其他任何东西.. 这将写入每个文件,但是你应该添加一些东西来检查成绩是否真的是一个数字(否则这可能会引发异常)..

    public static void SaveToFile()
    {
        string studentName;
        int studentMark;
        BinaryWriter nameFile;
        BinaryWriter markFile;

        nameFile = new BinaryWriter(new FileStream("studentNames.txt", FileMode.Create));
        markFile = new BinaryWriter(new FileStream("studentMarks.txt", FileMode.Create));
        Console.WriteLine("Enter a student name and a mark or, END to finish: ");

        Console.WriteLine("Enter student name: ");
        studentName = Console.ReadLine();

        while (studentName.ToUpper() != "END")
        {
            nameFile.Write(studentName + Environment.NewLine);

            Console.WriteLine("Enter mark: ");
            studentMark = Convert.ToInt32(Console.ReadLine());
            markFile.Write(studentMark + Environment.NewLine);

            Console.WriteLine("Enter student name: ");
            studentName = Console.ReadLine();
        }
        nameFile.Close();
        markFile.Close();
        return;
    }