Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 559
Mantas Avatar asked Oct 15 '25 18:10

Mantas


2 Answers

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...
}
like image 167
David Pine Avatar answered Oct 17 '25 08:10

David Pine


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

like image 36
Marc Avatar answered Oct 17 '25 09:10

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!