Question

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?

Était-ce utile?

La solution 2

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.

Autres conseils

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top