'Why does saving args[0] into a string give out a index-out-of-range exception?

I've tried to save args[0] into string lemon, but whatever I tried it didn't work at all, it instead threw an IndexOutOfRange exception:

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. at NHBloater.Program.Main(String[] args) in C:\Users...\Program.cs:line 12

I tried:

  • catching it
  • adding if (args.Length > 0)
  • searching on Google and Stack Overflow

Edit: I fixed it but don't know how, and the code that's worrying me is output += inputArray[i]

Here is the code with the first line being line 10 without the attempts to fix it: c#:

static void Main(string[] args)
{
    string lemon = args[0];
    string input = File.ReadAllText(lemon);
    string[] inputArray = input.Split();
    string output = "";
    for (int i = 0; i < input.Length; i++) 
        for (int j = 0; j < Convert.ToInt32(args[2]); j++) 
            output += inputArray[i];
    File.WriteAllText(args[1], output);
}

Imported libraries:

  • System
  • System.IO
  • System.Text

Arguments:

"h.txt"
"h2.txt"
"5"


Solution 1:[1]

While args won't be null (See the green Tip box in the link), it might be an Array of length 0.

So args[0] doesn't exist because it refers to the first item in the array, which doesn't have any items.

If you are really setting it in "command line arguments" in Visual Studio and are really using debug mode - see this answer. Basically - make sure it's all on "Any CPU".

EDIT

Change

string[] inputArray = input.Split();

to

string[] inputArray = input.ToCharArray();

Solution 2:[2]

You are checking input.Length but you are accessing inputArray[i].

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Fildor