-2
        string input = "";
        string result = "";
        if (Directory.Exists(Path.GetDirectoryName(filePath)))
        {
            if (File.Exists(filePath))
            {
                input = File.ReadAllText(filePath).ToString();
                List<byte> bList = new List<byte>();
                for (int i = 0; i < input.Length; i += 8)
                {
                    bList.Add(Convert.ToByte(input.Substring(i, 8), 2));
                }
                result = Encoding.UTF8.GetString(bList.ToArray());
                return result;

            }

Exception occurs in Substring inside the for loop Help me to get rid of this exception. Thanks in Advance

  • 3
    when the string is reaching the end it tried to read 8 characters and there is not enouch characters left. – Jonathan Alfaro Jun 07 '21 at 16:33
  • 1
    Does this answer your question? [What is an "index out of range" exception, and how do I fix it?](https://stackoverflow.com/questions/24812679/what-is-an-index-out-of-range-exception-and-how-do-i-fix-it) –  Jun 07 '21 at 16:37

1 Answers1

0

You are trying to access a substring without verifying that there are enough characters in the string to do so.

Let's say the file contains 6 characters. That means input.Length is 6. The first iteration of the for loop will make this method call: input.Substring(0, 8). However, the string only has 6 characters in it, so you get an ArgumentOutOfRangeException.

Stephen Jennings
  • 12,494
  • 5
  • 47
  • 66
  • FYI the second time the `i < input.Length` check is done is after the first `i += 8` so the only time the code works is when it is a multiple of 8. – juharr Jun 07 '21 at 16:43
  • @juharr You are of course correct. Wow, what a brain fart on my part. Thank you, I've removed the incorrect bits. – Stephen Jennings Jun 07 '21 at 23:32