How would you loop through a file until a particular sequence of characers is found in a C# console application?

I am writing a C# console application.

A snippet of my code is as follows:

var anchor1 = Encoding.UTF8.GetBytes("55ELRC");
var recordtype11 = Encoding.UTF8.GetBytes("11");
var bytes = File.ReadAllBytes(filePath);       (read in a file)
int irecordsize = 0252;
int x = 0;

How would you loop through the var titled bytes, in increments of irecordsize,
until bytes has the value sequence of anchor1 (value 55ELRC) and assign this column position at which
the anchor1 value is found to the integer variable x?

Column
------------
01 - 252             starts in 01 with '11'
235 - 504           starts in 235 with '44'
505 - 756           starts in 505 with '44'
757 - 1008         starts in 757 with '44'
1009 - 1260       starts in 1009 with '44'
1261 - 1512       starts in 1261 with '44'
1513 -  1764      starts in 1513 with '55ELRC'
zimmer9Asked:
Who is Participating?
 
jmcgOwnerCommented:
Sorry, I was thinking index in C, then went for C++, where it has a different name, and missed that you were in C#.

In C#, the method you want is String.IndexOf Method (String)
0
 
jmcgOwnerCommented:
This seems like an apropos place to use str::find

x = bytes.find(anchor1);

You may need to change your variables into type string.
0
 
zimmer9Author Commented:
Is str::find a C++ reference? I'm using C#.
0
 
zimmer9Author Commented:
I have to use a byte reader for my application.
0
 
jmcgOwnerCommented:
I'm not sure I understand what your constraint is, but perhaps a good method would be to read bytes one at a time into the buffer, checking only for the last char of anchor1. When you hit a match, check backwards in the buffer for the rest of anchor1 (by now, IndexOf will work on the buffer). This approach saves you from having to design a more complicated progressive comparison routine with backtracking. If you have to read in larger chunks, and you are not assured that the anchor will appear at the exact beginning of a chunk, you can similarly scan each chunk for the last char of anchor1 to decide whether it's necessary to check the accumulated buffer with IndexOf.

If you end up having to do this a lot, it would be worth knowing about Boyer-Moore:

http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.