3

I am creating a Windows Forms Application with c# that can open up a file on startup if it is passed an argument containing the path to the file.

However, it doesn't accurately determine if arguments have been passed. Even when I pass no arguments, it still tries to open up a file.

Here's my code:

string[] args = Environment.GetCommandLineArgs();
if (args == null || args.Length == 0)
{

}
else
{
    try
    {
        ListData ld = new LmReader.LmReader().readLmList(args[0]);
        listItemsList.Items.Clear();
        foreach (ListItemList li in ld.lil)
        {
            ListViewItem lvi = new ListViewItem(li.text);
            lvi.Font = li.itemFont;
            listItemsList.Items.Add(lvi);
        }
        filenameOpen = selectOpenLocation.FileName;
        this.Text = "List Maker - " + Path.GetFileNameWithoutExtension(args[0]);
    }
    catch (Exception ex)
    {
        new Error().doError("Your list could not be opened.", ex);
    }
}

What am I doing wrong?

i3arnon
  • 113,022
  • 33
  • 324
  • 344
Igor
  • 548
  • 3
  • 7
  • 24
  • 2
    What file does it try to open? Answering that question will surely tell you what you're doing wrong. – Gabe Jan 05 '14 at 16:23
  • Have you tried stepping through with a debugger or using `Debug.Trace` to look at the value of `args` at the start of that `if` block? – Katsuyuki Omuro Jan 05 '14 at 16:25
  • Offtopic: You could switch the if statement for compacter code. – Max Jan 05 '14 at 16:27

2 Answers2

6

Environment.GetCommandLineArgs() always at least returns one argument which is the excecutable file name and then contains the arguments you might have passed in.

So that's why your if condition nether matches

See documentation

MichaC
  • 13,104
  • 2
  • 44
  • 56
5

From the docs:

The first element in the array contains the file name of the executing program

Therefore

args.Length == 0

should be

args.Length <= 1

in your case.

keyboardP
  • 68,824
  • 13
  • 156
  • 205