Reputation: 107
I receive following error:
“unable to read beyond the end of stream”
I write the file like this:
FileStream path = new FileStream(@"C:\Users\Moosa Raza\Desktop\byte.txt", FileMode.CreateNew);
BinaryWriter file = new BinaryWriter(path);
int a = int.Parse(Console.ReadLine());
double b = double.Parse(Console.ReadLine());
string c = Console.ReadLine();
file.Write(b);
file.Write(c);
file.Write(a);
input is a = 12, b = 13 and c = raza
Then read it like this:
FileStream path = new FileStream(@"C:\Users\Computer\Desktop\byte.txt", FileMode.Open);
BinaryReader s = new BinaryReader(path);
int a = s.ReadInt32();
double b = s.ReadDouble();
string c = s.ReadString();
Console.WriteLine("int = {0} , double = {1} , string = {2}",a,b,c);
Console.ReadKey();
Upvotes: 0
Views: 9841
Reputation: 5008
please try this. By using 'using' scope, it will close the file when you finish writing or reading it. Also the code will be a bit cleaner.
using (var sw = new StreamWriter(@"C:\Users\Computer\Desktop\byte.txt"))
{
sw.WriteLine(int.Parse(Console.ReadLine()));
sw.WriteLine(double.Parse(Console.ReadLine()));
sw.WriteLine(Console.ReadLine());
}
using (var sr = new StreamReader(@"C:\Users\Computer\Desktop\byte.txt"))
{
int a = int.Parse(sr.ReadLine());
double b = double.Parse(sr.ReadLine());
string c = sr.ReadLine();
}
Upvotes: 0
Reputation: 151594
You must read the file in the exact same order you write it. According to your comment, the order in which you write is: double, string, int.
The reading code however, reads in the order int, double, string.
This causes the reader to read the wrong bytes, and interpret a certain value as an incorrect string length, thereby trying to read beyond the end of the file.
Make sure you read in the same order as you write.
Upvotes: 1