Binary byte read returning only one value. FROM#
The console displays 0,0,0,0 when I expect 0,1,2,3.
This is a modified version: https://msdn.microsoft.com/en-us/library/system.io.binarywriter(v=vs.110).aspx
using System;
using System.IO;
namespace testingfilereadwrite
{
class Program
{
const string FileName = "TestFile.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
Console.ReadKey();
}
public static void WriteDefaultValues()
{
using (BinaryWriter writer = new BinaryWriter(File.Open(FileName, FileMode.Create)))
{
writer.Write(0);
writer.Write(1);
writer.Write(2);
writer.Write(3);
}
}
public static void DisplayValues()
{
byte byte1;
byte byte2;
byte byte3;
byte byte4;
if (File.Exists(FileName))
{
using (BinaryReader reader = new BinaryReader(File.Open(FileName, FileMode.Open)))
{
byte1 = reader.ReadByte();
byte2 = reader.ReadByte();
byte3 = reader.ReadByte();
byte4 = reader.ReadByte();
}
Console.WriteLine(byte1);
Console.WriteLine(byte2);
Console.WriteLine(byte3);
Console.WriteLine(byte4);
}
}
}`
Why is only 0 displayed? How can I get it to display what I need? Also, why does this work when I use something other than a byte like string or int.
+3
source to share
2 answers
Since you are writing integers to a file and the first 4 bytes are 0.
public static void WriteDefaultValues()
{
using (BinaryWriter writer = new BinaryWriter(File.Open(FileName, FileMode.Create)))
{
writer.Write((byte)0);
writer.Write((byte)1);
writer.Write((byte)2);
writer.Write((byte)3);
}
}
Try it.
+6
source to share
When writing to a data file:
public static void WriteDefaultValues()
{
using (BinaryWriter writer = new BinaryWriter(File.Open(FileName, FileMode.Create)))
{
writer.Write(0);
writer.Write(1);
writer.Write(2);
writer.Write(3);
}
}
You are actually writing an integer (4 bytes) to the file.
So when you read, you read the first 4 bytes of your file, which is your zero that you wrote (0x00, 0x00, 0x00, 0x00). In your write method, supply the values ββin bytes and you will get the expected results.
public static void WriteDefaultValues()
{
using (BinaryWriter writer = new BinaryWriter(File.Open(FileName, FileMode.Create)))
{
writer.Write((byte)0);
writer.Write((byte)1);
writer.Write((byte)2);
writer.Write((byte)3);
}
}
+5
source to share