二进制读取循环在最后一次输入后继续

时间:2016-02-14 00:50:12

标签: c# loops while-loop binary

我尝试使用带有下面代码的while循环从二进制文件中读取,但由于某种原因,循环在最后一个条目之后不会中断。共有4个条目,每个条目都在一行中,每行都有以下格式。

  

StudentID StudentName StudentSurname StudentEmail StudentYear GPA

创建过滤器文件的功能。

public bool createGPAFilterFile(string fileName, string GPAFilterFileName, double lowerGPA, double upperGPA){            
        try
        {   
            MainClass sideObj = new MainClass();
            sideObj.createBinaryFile(GPAFilterFileName);
            FileStream stream = File.Open(fileName, FileMode.Open);
            BinaryReader reader = new BinaryReader(stream);

            while (stream.CanRead)
            {
                double readGPA = reader.ReadDouble();

                if (readGPA > lowerGPA && readGPA < upperGPA)
                {
                    UInt32 readStudentID = reader.ReadUInt32();
                    String readStudentName = reader.ReadString();
                    String readStudentSurname = reader.ReadString();
                    String readStudentEmail = reader.ReadString();
                    Byte readStudentYear = reader.ReadByte();
                    sideObj.appendToFile(GPAFilterFileName, readStudentID, readStudentName, readStudentSurname, readStudentEmail, readStudentYear, readGPA);
                }

            }
            reader.Close();
            reader.Dispose();
            stream.Close();
            stream.Dispose();
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message + "\n" + ex.Source);
            return false;
        }
    }

我首先用于追加数据的功能。

public bool appendToFile (string fileName, UInt32 studentID, string name, string surname, string email, byte classYear, double gpa){ 
        if (!File.Exists (fileName)) {
            bool success = createBinaryFile (fileName);
            if (!success) {

                return false;
            }
        }
        try{
            BinaryWriter writer = new BinaryWriter (File.Open (fileName, FileMode.Append));
            writer.Write (studentID);
            writer.Write (name);
            writer.Write (surname);
            writer.Write (email);
            writer.Write (classYear);
            writer.Write (gpa);
            writer.Close ();
            writer.Dispose ();
            return true;
        }
        catch{
            return false;
        }

    }

1 个答案:

答案 0 :(得分:0)

找到感兴趣的其他人的解决方案:)

而不是使用,while(stream.CanRead)我尝试使用while(stream.Position != stream.Length),现在代码正常运行。