有没有办法从文件中读取特定字节?
例如,我有以下代码来读取文件的所有字节
byte[] test = File.ReadAllBytes(file);
我想读取偏移量50到偏移量60的字节并将它们放在一个数组中。
答案 0 :(得分:47)
创建一个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);
}
答案 1 :(得分:28)
这应该这样做
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
。
答案 2 :(得分:13)
LINQ版本:
byte[] test = File.ReadAllBytes(file).Skip(50).Take(10).ToArray();
答案 3 :(得分:2)
你需要:
例如:
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;
}
}
答案 4 :(得分:1)
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;
}
答案 5 :(得分:1)
您可以使用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);
}
答案 6 :(得分:-3)
byte[] a = new byte[60];
byte[] b = new byte[10];
Array.Copy( a ,50, b , 0 , 10 );