有没有办法从文件中读取特定的字节?
例如,我有以下代码来读取文件的所有字节:
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();
IEnumerable<byte>
的文件名辅助函数来代替 File.ReadAllBytes
将是一种有效的方法。 - Richardpublic 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;
}
你可以使用文件流,然后调用读取函数
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);
}
FileStream.Read
的第二个参数是传递给第一个参数作为数组的偏移量,而不是文件中的偏移量。所以我的理解是正确的! :-) (代码现在会抛出异常,因为索引 50 超出了 bytes
的末尾。) - Richardbyte[] a = new byte[60];
byte[] b = new byte[10];
Array.Copy( a ,50, b , 0 , 10 );
reader.BaseStream.Seek(50, SeekOrigin.Begin);
。 - Tajomaru