using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
byte[] barr = null;
Console.WriteLine("\nread the first 13 bytes\n");
ReadBinaryFile("d:\\image.gif", 0, 13, ref barr);
PrintByteArray(barr);
Console.WriteLine("\n\nread the last 10 bytes\n");
ReadBinaryFile("d:\\image.gif", -10, 10, ref barr);
PrintByteArray(barr);
Console.WriteLine("\n\nread from byte 30 5 bytes \n");
ReadBinaryFile("d:\\image.gif", 30, 5, ref barr);
PrintByteArray(barr);
Console.WriteLine("\n\nread from byte 15 30000 bytes\n");
ReadBinaryFile("d:\\image.gif", 15, 3000, ref barr);//will show nothing, file size is < 30000
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
}
static void ReadBinaryFile(string file, int start, int len, ref byte[] barr)
{
using (BinaryReader br = new BinaryReader(File.Open(file, FileMode.Open)))
{
int total_len = (int)br.BaseStream.Length, pos = 0;
if (start >= 0)
pos += start;
else
pos = total_len - Math.Abs(start);
len = pos + len;
if (len > total_len) return;
br.BaseStream.Seek(pos, SeekOrigin.Begin);
int i = 0;
barr = new byte[len - pos];
while (pos++ < len)
{
barr[i++] = br.ReadByte();
}
}
}
static void PrintByteArray(byte[] barr)
{
for (int i = 0; i < barr.Length; i++)
Console.Write("{0,4}", barr[i]);
}
}
}
/*
run:
read the first 13 bytes
71 73 70 56 57 97 8 32 10 32 112 32 32
read the last 10 bytes
32 128 255 32 170 32 32 170 51 32
read from byte 30 5 bytes
135 32 32 32 32
read from byte 15 30000 bytes
*/