Journal: Software Development

Email: mail@appsoftware.com

Software development notes and articles

A journal for sharing all things software development related


Running C# as scripts using dotnet-script

Wed, 07 Aug 2019 11:56 UTC

Reference docs:

https://www.hanselman.com/blog/CAndNETCoreScriptingWithTheDotnetscriptGlobalTool.aspx

https://github.com/filipw/dotnet-script

Running dotnet-script

To run C# scripts using dotnet-script, you need to have the .NET Core 2.2 runtime installed.

If you do not have dotnet-script installed you can then install the tool using:

dotnet tool install -g dotnet-script

Navigate your terminal to the directory containing the script.

Run > dotnet script app.csx

Running remotely

Since dotnet-script allows for running of scripts from remote locations, you can run a .csx script from a remote file location.

Example app: https://github.com/garethrbrown/vs-project-rename

> dotnet script https://raw.githubusercontent.com/garethrbrown/vs-project-rename/master/src/dotnet-script/app.csx

Debugging

Follow instructions for setting up dotnet script here:

https://github.com/filipw/dotnet-script

Use the following to create base launchSettings.json file. This will create a debug configuration that you can use to debug the current script file that's in view using F5.

$ dotnet script init

Console input when debugging

Note that without some modifications to launchSettings.json, you may have have problems getting Console.Read() to work.

https://github.com/OmniSharp/omnisharp-vscode/issues/1053

Add the lines to launchSettings.json

"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",

E.g.

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": ".NET Script Debug",
            "type": "coreclr",
            "request": "launch",
            "program": "dotnet",
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "args": [
                "exec",
                "C:/Users/<user>/.dotnet/tools/.store/dotnet-script/0.30.0/dotnet-script/0.30.0/tools/netcoreapp2.1/any/dotnet-script.dll",
                "${file}"
            ],
            "cwd": "${workspaceRoot}",
            "stopAtEntry": true
        }
    ]
}

This will send ouput (and allow input) through the integrated terminal in VSCode. Note the distinction between debug console and integrated terminal. The second line stops VSCode from switching to the debug console when debugging is started.

The information on this site is provided “AS IS” and without warranties of any kind either express or implied. To the fullest extent permissible pursuant to applicable laws, the author disclaims all warranties, express or implied, including, but not limited to, implied warranties of merchantability, non-infringement and suitability for a particular purpose.