简体   繁体   English

使用C#进行十六进制值查找

[英]Hex Value Find with C#

I'm trying to search for an hex value inside a file, if that value is present I need to copy 16 bytes of char from that found position. 我正在尝试在文件内搜索一个十六进制值,如果存在该值,我需要从找到的位置复制16个字节的char I'm trying to do the same in C#. 我正在尝试在C#中执行相同的操作。

Please find my tried code below, correction will be greatly appreciated. 请在下面找到我尝试过的代码,我们将不胜感激。

BinaryReader bw = new BinaryReader(File.OpenRead(filepath));
byte[] bc = { 0xa0, 0x00, 0x00, 0x03 };
for (int i = 0; i < br.BaseStream.Length-10;i++)
{

if (bw.ReadUInt32() == 0xa00003)
{
    Console.WriteLine("Found @ {0}", i);

}

bw.Close();

I"m getting an error as follows: 我收到如下错误:

An unhandled exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll mscorlib.dll中发生了类型为'System.IO.EndOfStreamException'的未处理异常

Additional information: Unable to read beyond the end of the stream. 附加信息:在流的末尾无法读取。

The error is caused by the fact that your for loop has step equal to 1 and you are reading 4 bytes at a time. 该错误是由于您的for循环具有等于1的步长并且您一次读取4个字节而引起的。 After reading, the Stream position is advanced by 4. Change your for loop to the following one: 读取后,Stream位置前进4。将for循环更改for以下位置:

for (int i = 0; i < br.BaseStream.Length - 10; i += 4)
{
    //...
}

EDIT: 编辑:

If you want to search at every position without skipping 4 bytes every time, use the following code: 如果要在每个位置搜索而不每次都跳过4个字节,请使用以下代码:

    Stream f = File.OpenRead(fileName);
    BinaryReader br = new BinaryReader(f);
    for (int i = 0; i < f.Length - 10; i++)
    {
        f.Seek(i, SeekOrigin.Begin);
        if (br.ReadUInt32() == 0xa00003)
        {
            Console.WriteLine("Found @ {0}", i);
        }
    }
    br.Close();

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

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