0

I am following this tutorial on how to allow my program to open files using the "Open With" method found in Windows. However, as soon as the program loads, it crashes with the error "IndexOutOfRangeException".

My code is as follows.

public static void Main(string[] args)
    {
        if(args[0] != null)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Basic_Word_Processor());
            Basic_Word_Processor.Instance.richTextBoxPrintCtrl1.LoadFile(@args.ToString());
        }
        else
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Basic_Word_Processor());
        }

What is causing this exception to occur?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Toby
  • 377
  • 1
  • 10
  • 23

1 Answers1

5

this: args[0] because when args are null you are trying to access first element of array that does not exists.

So to fix you program you have to check if args is not null:

if(args != null && args.Length > 0)
{
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Basic_Word_Processor());
            Basic_Word_Processor.Instance.richTextBoxPrintCtrl1.LoadFile(args[0].ToString());
}
else
{
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Basic_Word_Processor());
}
gzaxx
  • 17,312
  • 2
  • 36
  • 54
  • 2
    Do you not need to check if the Length is zero as well? If it were Null then it would be a Null Reference Exception surly? – VisualMelon May 19 '13 at 10:31
  • Thanks. It doesn't crash now. The only issue now is that it still doesn't load the file when the "Open With" method is used. – Toby May 19 '13 at 10:38
  • Because you have to pass command-line arguments to program, one way of doing that is: start -> run -> /program.exe "c:\test.txt" or through project properties in visual studio – gzaxx May 19 '13 at 10:47
  • The issue with that is that I would like the user to be able to select a .rtf document and then be able to right click > open with > Basic Word Processor, instead of having to go through Run.. in order to do so. – Toby May 19 '13 at 11:05
  • Put breakpoint at start of your program and see what is passed inside args. – gzaxx May 19 '13 at 11:08