Use command line arguments to open files in C#


[command line arguments]

Whenever a C# program starts, it receives command line arguments. You can use those arguments to let your program open files that are associated with the program.

For example, when you double-click a .doc or .docx file, Microsoft Word opens and displays the file. You can use command line arguments to do something similar with your programs. Before you learn how to do that, you should know how you can send arguments to the program. (If you already know how you can send one or more files to a program, skip down to the next section.)

Opening With Arguments

Whenever a C# program starts, it receives command line arguments. The first argument is always the name of the program that is executing. Any remaining arguments depend on how you start the program. There are several ways that you can pass command line arguments to the program interactively.

If you double-click on the program, it the program’s name is the only argument that the program receives.

If you open a command window, you can type the program’s name followed by any arguments that you want to pass to the program. This is the most obvious but least convenient way to send arguments to the program.

If you drag-and-drop one or more files onto the program, then the program receives the files’ names as parameters.

In a similar technique, suppose you select one or more files in File Explorer. Then if you right-click the files, you can select Open With to see a sub-menu listing programs that the system thinks might be able to open the file. If you click Choose Another App, then you get a popup listing some apps that you might be able to use. Note that this popup also has a checkbox labeled “Always use this app to open .XXX files.” More on this later.

If you scroll to the bottom of the popup dialog, you’ll find a More Apps choice. (For some reason, Microsoft has made this option pale blue on a white background so it’s hard to see. Maybe it’s different if you’re using a different color scheme.) If you click this, you’ll get (you guessed it) more apps! At the bottom of the new list, there’s yet another pale blue option: Look for another app on this PC. If you get this far without growing bored and wandering away, you get a file selection dialog that lets you pick your program. If you select the program and click Open, then File Explorer opens your program and sends it (as command line arguments) the names of the files that you originally right-clicked so long ago.

Here’s a summary of this process.

  1. Select one or more files.
  2. Right-click.
  3. Select Open With > Choose Another App.
  4. Check the “Always use this app to open .XXX files” box if you like, scroll to the bottom, and select More Apps.
  5. Scroll to the bottom and select “Look for another app on this PC.”
  6. Use the file selection dialog to find the executable program, select it, and click Open.

Whew!

If you go through that whole process and you check the “Always use this app to open .XXX files” box, then later you can double-click on a .XXX file to open the program. In that case, the name of the file that you double-clicked is passed to the program as a command-line argument.

If you followed the process and checked the box, you can also select one or more files, right-click them, and select Open. Again your program starts and it receives the file name(s) in the command line arguments.

If you place a shortcut to your program in the SendTo directory, then you can right-click files and use SendTo to send them to your program.

If you create a shortcut to your program, you can right-click the shortcut, select Properties, and enter command line arguments in the Target text box after the file’s name.

There are probably many other methods for interactively launching a program with command line arguments. There are also some non-interactive methods. For example, you can use the System.Diagnostics.Process class to start a process. You can set the object’s StartInfo.Arguments property before you call the Start method to pass the program command line arguments.

There are probably many other ways to start programs interactively or non-interactively, but this is more than enough for now. WAY more than enough! There’s just one more way to do this that you really need to know about.

Command Line Arguments in Visual Studio

You can pass command line arguments to your program when you run it in Visual Studio. That’s important because that’s the easiest way to test and debug how your program handles those arguments.

To set the arguments, open the Project menu and select Properties. On the Properties window, select the Debug tab and enter values in the Command Line Arguments text box as shown in the following picture.


[command line arguments]

Separate the values with spaces. If a value should contain a space, enclose the value in quotes.

Now when you start the program inside Visual Studio, it will receive the command line arguments that you entered.

Loading Files

That’s enough ways to send arguments to the program. It’s time to talk about your program.

The program should be able to open some kind of file. It could be a serialization of some sort, a data file with a special format, whatever.

This example loads drawing serializations. It extends the example Save and restore line drawings in C#. The original program’s File > Open menu item loaded a file containing lines. The new version of the program moves the code that loads the file into the following method.

// Open the file.
private void LoadFile(string filename)
{
    try
    {
        XmlSerializer xml_serializer = new XmlSerializer(TheDrawing.GetType());
        using (FileStream file_stream = new FileStream(filename, FileMode.Open))
        {
            Drawing new_drawing =
                (Drawing)xml_serializer.Deserialize(file_stream);
            TheDrawing = new_drawing;
            picCanvas.Refresh();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

This code creates a serializer to work with the class named Drawing. The object TheDrawing is of that type. The program opens a file stream to the drawing file, deserializes the stream into a new Drawing object, saves the drawing in the variable TheDrawing, and redraws the program’s PictureBox to show the lines.

Now the File > Open menu command displays an open file dialog and calls the LoadFile method to load the selected file.

Your program may do something different, but it will be easier if you have a method similar to the one above that loads a file.

Processing Command Line Arguments

When the program starts, the following Load event handler executes to handle the command line arguments.

private void Form1_Load(object sender, EventArgs e)
{
    string[] args = Environment.GetCommandLineArgs();
    if (args.Length < 2)
    {
        // We have no command line arguments.
        // Do nothing.
        return;
    }

    // Open the first file.
    MessageBox.Show("Opening [" + args[1] + "]");
    LoadFile(args[1]);

    // If we have more than one file name,
    // load them in their own instances.
    for (int i = 2; i < args.Length; i++)
    {
        // See: Open a file with the system’s default application in C#
        // http://csharphelper.com/blog/2014/08/open-a-file-with-the-systems-default-application-in-c/
        try
        {
            MessageBox.Show("Spawning [" + args[i] + "]");
            System.Diagnostics.Process.Start(args[0], args[i]);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

This code first checks the length of the command argument array. If the array contains a single value, then it is the program’s name. In that case the program does not need to load any files so the event handler simply returns.

Next the code displays a message to let you know what it is doing and then calls the LoadFile method, passing it the first command line argument. That argument will be the name of the first file passed to the program.

The code then loops through any remaining command line arguments. For each argument the code displays a message box and uses System.Diagnostics.Process.Start to execute the program, which has the path stored in args[0]. It passes the value in args[i] in as a command line argument. When the new instance of the program starts, it has a single parameter so the program just loads it.

Now if you somehow pass multiple files to the program, the program loads the first one and launches copies of itself to load the others.

(After you have your program working correctly, remove the message boxes that tell you what the program is doing.)

Conclusion

It’s not too hard to make a program load multiple files when it starts. It checks its command line arguments and loads the file names in args[1]. Then if there are more arguments, the program can launch copies of itself to handle the other files.

Download the example program and give it a try. Try selecting the sample files test.lines, test2.lines, and test3.lines and then dragging them onto the executable program.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in serialization, system and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.