繁体   English   中英

读取文件的特定字节

[英]Read specific bytes of a file

有没有办法从文件中读取特定字节?

例如,我有以下代码来读取文件的所有字节:

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

我想读取从偏移量 50 到偏移量 60 的字节并将它们放入一个数组中。

创建一个 BinaryReader,从字节 50 开始读取 10 个字节:

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

这应该做

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将包含文件偏移量 50 和 60 之间的 10 个字节,而actualRead将包含一个从 0 到 10 的数字,表示实际读取了多少字节(当文件至少有 50 但小于 60 时,这很有趣)字节)。 如果文件小于 50 字节,您将看到EndOfStreamException

LINQ版本:

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

你需要:

  • 寻找你想要的数据
  • 重复调用 Read,检查返回值,直到获得所需的所有数据

例如:

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

您可以使用文件流,然后调用 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM