Mantas
Mantas

Reputation: 191

Command line arguments using in Windows form

I have C# Windows form application, I am doing a lot of check boxes and write and read them to JSON format file called test.json. Now I want to use my test.json with program.exe, that my program.exe would get check box checked as written in test.json. So I create Load event handler and want to use my GetCommandLineArgs().

private void Form1_Load(object sender, EventArgs e)
{
    string[] args = Environment.GetCommandLineArgs();            
}

I know that I have 2arguments.[0] - program.exe and [1] - test.json. Need some ideas how to make it work.

My question is:

How to make that args list of 2elements. Where 0 is program.exe and 1 is test.json. And how to work with args.length when there is possibility that there will be no parameters or only one parameter

Upvotes: 4

Views: 7922

Answers (2)

Marc
Marc

Reputation: 4803

Something like this:

var cmdArgs = Environment.GetCommandLineArgs();

if (cmdArgs.Length < 2) 
{
    MessageBox.Show("No JSON file specified!");
}

var jsonFilename = cmdArgs[1];

If you do more complex command line parameter parsing I suggest to use an existing library like this one.

Update:

Here is where you can attach your event-handler (or create a new one doing a double-click):

enter image description here

Upvotes: 3

David Pine
David Pine

Reputation: 24525

How to make that args list of 2 elements. Where 0 is program.exe and 1 is test.json

To do this you can debug from within visual studio by opening the project properties window and navigating to the Debug tab, from within there you can specify the command line args you want as shown below:

Entering command line arguments for debugging

You can use the Environment.GetCommandLineArgs(), it is a little odd in my opinion. It provides to you the executable name that is currently running. So in your case you would end up with exactly what you're asking for.

[0] - program.exe and [1] - test.json

How to work with args.Length when there is possibility that there will be no parameters or only one parameter.

This is simple, the Environment.GetCommandLineArgs() returns a string[]. Check for the desired length and handle it accordingly.

var commandLineArgs = Environment.GetCommandLineArgs();
if (commandLineArgs.Length > 0)
{
    // Do something magical...
}
else
{
    // Nothing was passed in...
}

Upvotes: 4

Related Questions