0

So, this is a part of a larger program but this is the code that is failing. Sometimes when I run the program everything works as intended, but sometimes for no apparent reason with the exact same file it throws the Index out of bound of array exception here:

string text1 = text.Substring(127761 * count, 122761);

The purpose of this block of code is to divide a large text file into smaller text file so the method _encrypt doesn't throw an error.

string text = File.ReadAllText(file);
if (text.Length > 127761)
{
    List<string> texts = new List<string>();
    int count = 1;

    for (int i = 0; i < text.Length; i++)
    {
        if (i == 127761 * count)
        {
            if (text.Length - 127761 * count >= 0)
            {
                string text1 = text.Substring(127761 * count, 122761);
                texts.Add(text1);
                count++;
            }
        else texts.Add(text.Substring(127761 * count));
    }
}

for (int i = 0; i < texts.Count; i++)
{
    File.WriteAllText(desktop_path + @"\encrypt" + (i + 1) + ".txt", texts[i]);
    _encrypt(desktop_path + @"\encrypt" + (i + 1) + ".txt", where_to_place + @"\part" + (i + 1));
}

If anyone can help me I would be grateful

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 7
    To me, this sounds like something you can solve by yourself by [using a debugger](https://learn.microsoft.com/en-us/visualstudio/debugger/getting-started-with-the-debugger?view=vs-2017). I.e. let it break on exceptions and then inspect the current variable values and the stack trace. – Uwe Keim Aug 23 '18 at 14:22
  • 1
    It looks like it will fail if you text has less than this multiplication (magic value of 127761 * count) characters. – Dimitar Aug 23 '18 at 14:25
  • 1
    Perhaps you can rewrite your encrypt function instead so it does not throw error on large files. If you post it we can help you. – Magnus Aug 23 '18 at 14:25
  • 1
    this code also looks super messy. that `else` statement, where does it belong? if it belongs to the `if` right above it (which i suspect it does), you are missing a ` }` that should close the *first* `if` in your example – Timothy Groote Aug 23 '18 at 14:28
  • I've linked a dupe that includes both loop based and LINQ based answers to what appears the *problem* to solve here. – Damien_The_Unbeliever Aug 23 '18 at 14:28
  • use the debugger and step thru the code, if at the very least, google what things could cause `Index Out of Bounds` errors the problem is in your for loop within the else part – MethodMan Aug 23 '18 at 14:28
  • But if you did want to work with this code, you are aware that you don't have to write `i++` in your for loop, aren't you? You could for instance have `i+=127761`. Then you'd just have to re-write your substringing logic to use `i` as one end and `MIN(remaining length, 127761)` for the length – Damien_The_Unbeliever Aug 23 '18 at 14:30

0 Answers0