6
Answers

Writing and then reading a binary- inconsistency/incorrect

Sahil Dev

Sahil Dev

8y
289
1
  1. public void WritingABinaryBun() ///Writing  
  2.         {  
  3.    
  4.   System.IO.FileStream wFile;  
  5.                 wFile = new FileStream(Path.Combine(OuputsPath, "SC03Brick201.bun"), FileMode.Create);  
  6.                 byte[] bytes = BitConverter.GetBytes(-1);  
  7.                 if (BitConverter.IsLittleEndian) Array.Reverse(bytes);  
  8.                 wFile.Write(bytes, 0, bytes.Length);  
  9.   
  10.                  bytes = BitConverter.GetBytes(10);  
  11.                 if (BitConverter.IsLittleEndian) Array.Reverse(bytes);  
  12.                 wFile.Write(bytes, 0, bytes.Length);  
  13.   
  14.                 bytes = BitConverter.GetBytes(164);  
  15.                 if (BitConverter.IsLittleEndian) Array.Reverse(bytes);  
  16.                 wFile.Write(bytes, 0, bytes.Length);  
  17. }  
  18.   
  19.   
  20.  public void ReadingABinaryBun() //Reading  
  21.         {  
  22.   
  23.             using (BinaryReader b = new BinaryReader(File.Open(Path.Combine(InputsPath, "SC03Brick201.bun"), FileMode.Open)))  
  24.             {  
  25.   
  26.                 int pos = 0;  
  27.   
  28.                 int length = (int)b.BaseStream.Length;  
  29.                 //long length1 = (long)b.BaseStream.Length;  
  30.   
  31.                 while (pos < length)  
  32.                 {  
  33.                     int v = b.ReadInt32();  
  34.                     //double v1 = b.ReadDouble();  
  35.   
  36.                     pos += sizeof(int);  
  37.   
  38.   
  39.   
  40.                 }  
  41.             }  
  42.   
  43.   
  44.   
  45.         }  
 

Below are 2 code snippets (which are a concise form of my code) which I'm using for writing and reading a binary file.

 
As you see, I have written 3 integer values into a binary file.
 
 
But when I read the same file through the second code snippet, I see only the foirst integer value of -1 is correctly read in.
 
Can anybody please help em understand why is it so?
 
I am using C# 

Answers (6)