To read binarydata from a file in C#, you typically use one of the following:
1. File.ReadAllBytes()
Reads the entire file into a byte array.
byte[] data = File.ReadAllBytes(@"C:\path\to\file.bin");
Simple and useful when the entire file can fit in memory.
Returns a byte[].
2. FileStream (for reading in chunks or large files)
Gives more control for reading part of the file or working with large files.
using (FileStream fs = new FileStream(@"C:\path\to\file.bin", FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[fs.Length];
int bytesRead = fs.Read(buffer, 0, buffer.Length);
}
You can also read in smaller chunks if fs.Length is too large.
3. BinaryReader (for structured binary data)
Useful if you're reading primitives like integers, floats, strings, etc., from a binary format.
using (FileStream fs = new FileStream(@"C:\path\to\file.bin", FileMode.Open, FileAccess.Read))
using (BinaryReader reader = new BinaryReader(fs))
{
int value = reader.ReadInt32(); // Reads a 4-byte int
double d = reader.ReadDouble(); // Reads an 8-byte double
byte[] bytes = reader.ReadBytes(10); // Reads 10 bytes
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To read binary data from a file in C#, you typically use one of the following:
1.
File.ReadAllBytes()Reads the entire file into a byte array.
byte[].2.
FileStream(for reading in chunks or large files)Gives more control for reading part of the file or working with large files.
You can also read in smaller chunks if
fs.Lengthis too large.3.
BinaryReader(for structured binary data)Useful if you're reading primitives like integers, floats, strings, etc., from a binary format.
Summary
File.ReadAllBytesFileStreamBinaryReader