Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:
Why do I always get this error:
'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'
Here's the code:
C#
class Program
{
    public static string PathLocation = "D:" + Path.DirectorySeparatorChar + "MyTestFile.myfile";

    static void Main(string[] args)
    {
        Console.Title = "File testing";
        Console.WriteLine("Continue with test...");

        if (Console.ReadKey().Key == ConsoleKey.Enter)
        {
            Console.Clear();
        }

        System.IO.BinaryWriter writer = new BinaryWriter(new FileStream(PathLocation, FileMode.Create));

        writer.Write(ByteHelp.CreateByte("00101010"));

        writer.Close();

        Console.WriteLine("File has been created at: " + PathLocation);
        Console.WriteLine("Test has been successful!");
        Console.WriteLine();
        Console.WriteLine("Read binary?");

        if (Console.ReadKey().Key == ConsoleKey.Enter)
        {
            Console.Clear();
        }

        System.IO.BinaryReader reader = new BinaryReader(new FileStream(PathLocation, FileMode.Open));
        Console.WriteLine(Convert.ToString(reader.ReadByte(), 2).PadLeft(8, '0'));
        Console.WriteLine();
        Console.WriteLine("Exit...");
        Console.ReadKey();
    }
}


C#
public sealed class ByteHelp
{
    public static byte CreateByte(string bits)
    {
        if (bits.Length != 8)
        {
            throw new ArgumentException("There must be only 8 bits.");
        }

        bool[] boolBits = new bool[7];
        BitArray tempBits = new BitArray(boolBits);

        int count = 0;
        foreach (char character in bits)
        {
            if (character == '0')
            {
                tempBits.Set(count, false);
            }
            else if (character == '1')
            {
                tempBits.Set(count, true);
            }
            else
            {
                throw new Exception("The bit value must be a 1 or a 0.");
            }

            count += 1;
        }

        if (tempBits.Count != 8)
        {
            throw new ArgumentException("There must be only 8 bits.");
        }

        byte[] bytes = new byte[1];
        tempBits.CopyTo(bytes, 0);
        return bytes[0];
    }
}
Posted
Comments
Which line throws the exception?
Sergey Alexandrovich Kryukov 14-Dec-13 2:20am    
Execute it under the debugger, and you will immediately see what's going on, and will be able to fix it. This is one of the easiest issues.
—SA
IAmABadCoder 14-Dec-13 2:35am    
I've done that but am still confused about what's going wrong.
Sergey Alexandrovich Kryukov 14-Dec-13 13:14pm    
If you really did it, you would at least know in what line you go out of range, but you did not tell it even now.
—SA
An@nd Rajan10 14-Dec-13 5:16am    
which line have error please mention it, that is helps to more accurate solution

1 solution

Um.

You ran this in the debugger and you can;t work it out?
So did I...

It throws the exception at this line:
C#
tempBits.Set(count, false);
Because you rpovide it with a string of eight bits:
C#
writer.Write(ByteHelp.CreateByte("00101010"));
                                  12345678
And only allow for 7 in your bool array:
C#
bool[] boolBits = new bool[7];
So when you try to write the eighth bit (count == 7) it doesn't have anywhere to put it...
Change this line:
C#
bool[] boolBits = new bool[7];
To this:
C#
bool[] boolBits = new bool[bits.Length];
And that problem will go away.

But...two things:
1) You do realize that it probably stuffs the bits in the wrong order? So in your example the result will be Hex 54, not Hex 2A?
2) There is a built in function to convert a binary string to a byte:
C#
byte b = Convert.ToByte("00101010", 2);
 
Share this answer
 
Comments
IAmABadCoder 21-Dec-13 2:01am    
Oops, i thought when you converted it as a string ToByte("00101010", 2) it would have converted it as the equivalent string value. Sorry if I am not making much sense.
OriginalGriff 21-Dec-13 5:38am    
No, no you are right - that doesn't make much sense! :laugh:
It's probably me (I need another coffee) but could you try explaining that in simple words so I can understand?
IAmABadCoder 21-Dec-13 7:03am    
:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900