Read 1 byte at a time from an array

Hello All

I'm still converting onto C# from COBOL and have managed to read a file of bytes into an array using the following;

byte[] allBytes = File.ReadAllBytes(openFileDialog1.FileName);

I'd now like to loop through the array, one byte at a time and check that byte to see if it contains binary zeroes. Any suggestions as to how I could do this If they are zeroes, I'd then like to jump 200 bytes forward and see if this bytes is also zeroes then take some action !

Thanks



Answer this question

Read 1 byte at a time from an array

  • LearningVisualC2005

    You can iterate through an array using foreach:


    foreach(byte b in allBytes)
    {
    if(b == 0)
    {
    // Do stuff
    }
    }

    If you want to check the first n bytes are zero, then use a for loop:


    bool allZero = true;
    for(int i = 0; i < n; i++)
    {
    if(allBytesIdea != 0)
    {
    allZero = false;
    break;
    }
    }

    if(allZero)
    {
    for(int i = 200; i < allBytes.Length; i++)
    {
    // Do stuff to bytes from 200 on
    }
    }



  • bolky

    Mark

    Many thanks - it's great to see code and how it works, very different to what I'm used to.

    Once inside the for loop, how do I actually check an individual byte In COBOL it would be something like allBytes(i) but I'm nit sure how to code this.

    Ta


  • DevanDanger

    Hi

    Sorry, this stupid forum software replaces probably the most common C# construct in existence with a light-bulb emoticon, even within code tags. I'm sure there's some way of stopping it, I just don't know what it is.

    Array indexers in C# are specified with square brackets: I'm adding spaces here to prevent the emoticon:


    for(int i = 0; i < allBytes.Length; i++)
    {
    Console.Write( allBytes[ i ] );
    }



  • WinFormsUser13232

    Perfect ! Works a treat. Now very happy with my first app.

    Thanks.


  • Read 1 byte at a time from an array