8

I'm using csi.exe the C# Interactive Compiler to run a .csx script. How can I access any command line arguments supplied to my script?

csi script.csx 2000

If you're not familiar with csi.exe, here's the usage message:

>csi /?
Microsoft (R) Visual C# Interactive Compiler version 1.3.1.60616
Copyright (C) Microsoft Corporation. All rights reserved.

Usage: csi [option] ... [script-file.csx] [script-argument] ...

Executes script-file.csx if specified, otherwise launches an interactive REPL (Read Eval Print Loop).
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
  • 2
    Possible duplicate of [How to use CSI.exe script argument](https://stackoverflow.com/questions/38060860/how-to-use-csi-exe-script-argument) – binki Oct 18 '17 at 15:44

3 Answers3

12

CSI has an Args global which parses out the arguments for you. For most cases, this will get you the arguments you wanted as if you were accessing argv in a C/C++ program or args in the C# Main() signature static void Main(string[] args).

Args has a type of IList<string> rather than string[]. So you will use .Count to find the number of arguments instead of .Length.

Here is some example usage:

#!/usr/bin/env csi
Console.WriteLine($"There are {Args.Count} args: {string.Join(", ", Args.Select(arg => $"“{arg}”"))}");

And some example invocations:

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx
There are 0 args:

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx hi, these are args.
There are 4 args: “hi,”, “these”, “are”, “args.”

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx 'hi, this is one arg.'
There are 1 args: “hi, this is one arg.”
binki
  • 7,754
  • 5
  • 64
  • 110
1

Here is my script:

    var t = Environment.GetCommandLineArgs();
    foreach (var i in t)
        Console.WriteLine(i);

To pass in arguments to csx:

    scriptcs hello.csx -- arg1 arg2 argx

Prints out:

    hello.csx
    --
    arg1
    arg2
    argx

Key is '--' between csx and script arguments.

-1

Environment.GetCommandLineArgs() returns ["csi", "script.csx", "2000"] for that example.

Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
  • https://stackoverflow.com/a/38061368/429091 avoids the issues with trying to guess where arguments intended for the script start, so I would not recommend the method in this answer – binki Oct 18 '17 at 15:46