我尝试使用带有下面代码的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;
}
}
答案 0 :(得分:0)
而不是使用,while(stream.CanRead)
我尝试使用while(stream.Position != stream.Length)
,现在代码正常运行。