I have created a Class with constructor in which I pass the parameters as studentName, studentMarks & avgMarks and use Constructor to set the values and inside WriteData() method I use BinaryWriter to write the data to stud.dat file and after that I use ReadData() method inside that I use BinaryReader to read thr data from stud.dat file but while reading it shows me the wrong output like this:
Enter Student 1 Name: ABC
Enter Student 1 Subject 1 Marks: 85
Enter Student 1 Subject 2 Marks: 90
Enter Student 1 Subject 3 Marks: 95
Press Y to continue
y
Enter Student 2 Name: XYZ
Enter Student 2 Subject 1 Marks: 65
Enter Student 2 Subject 2 Marks: 70
Enter Student 2 Subject 3 Marks: 75
Press Y to continue
N
ABC 85 90 95 90
ABC 1515804675 65 70 75
What should I do so that I can retrieve my data back using BinaryReader and BinaryWriter. My code is:
using System;
using System.IO;
namespace BinaryWriterDemo
{
class BinaryTesting
{
FileStream fs;
string studentName;
int[] studentMarks = new int[3];
int avgMarks;
int numOfStudents = 0;
public BinaryTesting(string studentName, int[] studentMarks, int avgMarks)
{
this.studentName = studentName;
this.studentMarks = studentMarks;
this.avgMarks = avgMarks;
}
public void WriteData()
{
fs = new FileStream(@"/Users/swapnilnawale/Desktop/stud.dat", FileMode.Append, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(studentName);
for(int i = 0; i<3;i++)
{
bw.Write(studentMarks[i]);
}
bw.Write(avgMarks);
bw.Flush();
bw.Close();
fs.Close();
numOfStudents++;
}
public void ReadData()
{
fs = new FileStream(@"/Users/swapnilnawale/Desktop/stud.dat", FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
studentName = br.ReadString();
for (int j = 0; j <= numOfStudents; j++)
{
Console.Write(studentName + "\t");
for (int i = 0; i < 3; i++)
{
studentMarks[i] = br.ReadInt32();
Console.Write(studentMarks[i] + "\t");
}
avgMarks = br.ReadInt32();
Console.WriteLine(avgMarks);
}
br.Close();
fs.Close();
}
}
class Program
{
static void Main(string[] args)
{
string studentName;
int[] studentMarks = new int[3];
int i = 0, totMarks=0, avgMarks;
string resp;
BinaryTesting bt;
do
{
i++;
Console.Write("Enter Student {0} Name: ", i);
studentName = Console.ReadLine();
for(int j = 0; j<3;j++)
{
Console.Write("Enter Student {0} Subject {1} Marks: ", i, (j+1));
studentMarks[j]=Convert.ToInt32(Console.ReadLine());
totMarks += studentMarks[j];
}
avgMarks = totMarks / 3;
bt = new BinaryTesting(studentName, studentMarks, avgMarks);
bt.WriteData();
Console.WriteLine("Press Y to continue");
resp = Console.ReadLine();
} while (resp == "Y" || resp == "y");
bt.ReadData();
}
}
}