Подтвердить что ты не робот

С# - Чтение определенных байтов файла

Есть ли способ прочитать определенные байты из файла?

Например, у меня есть следующий код для чтения всех байтов файла

byte[] test = File.ReadAllBytes(file);

Я хочу прочитать байты от смещения 50 до смещения 60 и поместить их в массив.

4b9b3361

Ответ 1

Версия LINQ:

byte[] test = File.ReadAllBytes(file).Skip(50).Take(10).ToArray();

Ответ 2

Создайте BinaryReader, прочитайте 10 байт, начиная с байта 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);
}

Ответ 3

Это должно сделать это

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);
}

По завершении data будет содержать 10 байт между смещением файла 50 и 60, а actualRead будет содержать число от 0 до 10, указывая, сколько байтов было фактически прочитано (это интересно, когда файл имеет не менее 50, но менее 60 байт). Если файл меньше 50 байт, вы увидите EndOfStreamException.

Ответ 4

Вам необходимо:

  • искать нужные данные.
  • вызов Прочитайте повторно, проверяя возвращаемое значение, пока не получите все необходимые данные.

Например:

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;     
    }
}

Ответ 5

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;
 }

Ответ 6

Вы можете использовать filestream, а затем вызвать 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);
}

Проверьте этот пример MSDN

Ответ 7

byte[] a = new byte[60];
byte[] b = new byte[10];
Array.Copy( a ,50, b , 0 , 10 );