【发布时间】:2020-05-19 11:54:13
【问题描述】:
摘要
从块中读取文件中的字节(在 128 - 1024 之间没有特定大小,尚未决定),我想搜索缓冲区以查看它是否包含另一个字节数组的签名(模式),如果它在缓冲区的最后找到一些模式,它应该从文件中读取接下来的几个字节,看看它是否找到了匹配项
我的尝试
public static bool Contains(byte[] buffer, byte[] signiture, FileStream file)
{
for (var i = buffer.Length - 1; i >= signiture.Length - 1; i--) //move backwards through array stop if < signature
{
var found = true; //set found to true at start
for (var j = signiture.Length - 1; j >= 0 && found; j--) //loop backwards throughsignature
{
found = buffer[i - (signiture.Length - 1 - j)] == signiture[j];// compare signature's element with corresponding element of buffer
}
if (found)
return true; //if signature is found return true
}
//checking end of buffer for partial signiture
for (var x = signiture.Length - 1; x >= 1; x--)
{
if (buffer.Skip(buffer.Length - x).Take(x).SequenceEqual(signiture.Skip(0).Take(x))) //check if partial is equal to partial signiture
{
byte[] nextBytes = new byte[signiture.Length - x];
file.Read(nextBytes, 0, signiture.Length - x); //read next needed bytes from file
if (!signiture.Skip(0).Take(x).ToArray().Concat(nextBytes).SequenceEqual(signiture))
return false; //return false if not a match
return true; //return true if a match
}
}
return false; //if not found return false
}
这可行,但有人告诉我 linq 很慢,我应该使用 Array.IndexOf()。我已经尝试过了,但无法弄清楚如何实现它
【问题讨论】:
-
Linq 会占用大量内存,这会使某些查询运行缓慢。如果您只是在一个小数组上运行数据,那么在 linq 中可能会运行得更快。
标签: c# search buffer streamreader indexof