What are C# .CSX script files?

Posted: (EET/GMT+2)

 

Not all C# code needs to be compiled into assemblies. With the Roslyn compiler, you can now write and run C# script files. These are files that use the ".csx" file extension. They let you execute C# code directly, without creating a project or compiling the code first.

These scripts are supported by tools like the dotnet command-line utility and Visual Studio Code with the C# extension. They're perfect for quick experiments, automation scripts, or learning/testing scenarios.

To install the "dotnet script" tool, run the following command:

dotnet tool install -g dotnet-script

Ater this, you can start authoring C# script files with a .csx file extension. A simple .csx file might look like this:

// hello.csx
#r "System.IO"
using System;

string[] files = Directory.GetFiles(".");
foreach (string f in files)
{
    Console.WriteLine(f);
}

You can run it with:

dotnet script hello.csx

Unlike PowerShell or batch files, C# script files give you full access to .NET APIs, strong typing, and familiar syntax. You can also import NuGet packages dynamically using:

#r "nuget:PackageName,Version"

...which makes them extremely flexible.

For me, .csx files fill a nice gap between "throwaway PowerShell script" and "full Visual Studio project". They're simple, cross-platform, and surprisingly powerful for quick automation tasks.