Is there any way to read specific bytes from a file?
For example, I have the following code to read all the bytes of the file:
byte[] test = File.ReadAllBytes(file);
I want to read the bytes from offset 50 to offset 60 and put them in an array.
Is there any way to read specific bytes from a file?
For example, I have the following code to read all the bytes of the file:
byte[] test = File.ReadAllBytes(file);
I want to read the bytes from offset 50 to offset 60 and put them in an array.
Create a BinaryReader, read 10 bytes starting at byte 50:
byte[] test = new byte[10];
using (BinaryReader reader = new BinaryReader(new FileStream(file, FileMode.Open)))
{
reader.BaseStream.Seek(50, SeekOrigin.Begin);
reader.Read(test, 0, 10);
}
This should do it
var data = new byte[10];
int actualRead;
using (FileStream fs = new FileStream("c:\\MyFile.bin", FileMode.Open)) {
fs.Position = 50;
actualRead = 0;
do {
actualRead += fs.Read(data, actualRead, 10-actualRead);
} while (actualRead != 10 && fs.Position < fs.Length);
}
Upon completion, data
would contain 10 bytes between file's offset of 50 and 60, and actualRead
would contain a number from 0 to 10, indicating how many bytes were actually read (this is of interest when the file has at least 50 but less than 60 bytes). If the file is less than 50 bytes, you will see EndOfStreamException
.
LINQ Version:
byte[] test = File.ReadAllBytes(file).Skip(50).Take(10).ToArray();
You need to:
For example:
public static byte[] ReadBytes(string path, int offset, int count) {
using(var file = File.OpenRead(path)) {
file.Position = offset;
offset = 0;
byte[] buffer = new byte[count];
int read;
while(count > 0 && (read = file.Read(buffer, offset, count)) > 0 )
{
offset += read;
count -= read;
}
if(count < 0) throw new EndOfStreamException();
return buffer;
}
}
using System.IO;
public static byte[] ReadFile(string filePath)
{
byte[] buffer;
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
try
{
buffer = new byte[length]; // create buffer
fileStream.Read(buffer, 50, 10);
}
finally
{
fileStream.Close();
}
return buffer;
}
You can use filestream to and then call read
string pathSource = @"c:\tests\source.txt";
using (FileStream fsSource = new FileStream(pathSource,
FileMode.Open, FileAccess.Read))
{
// Read the source file into a byte array.
byte[] bytes = new byte[fsSource.Length];
int numBytesToRead = 10;
int numBytesRead = 50;
// Read may return anything from 0 to numBytesToRead.
int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
}
byte[] a = new byte[60];
byte[] b = new byte[10];
Array.Copy( a ,50, b , 0 , 10 );