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).
1

3 Answers 3

13

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.”
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

@binki this should be its own answer, not a comment.
@ChrisCharabaruk I have promoted it to an answer and removed my comment. Thanks!
0

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.