Run a .NET App from a Single C# File
Learn how to write and run a .NET app from a single C# script file, no project or solution required.
With .NET 10, you can run a C# file directly, no project or solution file required!
This is especially useful for automation scripts, DevOps tasks, or quick experimentation.
In this tutorial, I’ll show you how it works on macOS (or any supported Unix-based system).
Getting Started with dotnet app run.cs
First, install the .NET 10 SDK.
On macOS, you can use Homebrew:
brew install junian/dotnet/dotnet-sdk@10.0
Create a new file and make it executable:
touch hello_world.cs
chmod +x hello_world.cs
Open hello_world.cs
in your favorite editor (e.g., vim
). Add a shebang at the top so it can be executed directly:
#!/usr/bin/env dotnet run
Console.WriteLine("Hello, World!");
Save the file and run it:
$ ./hello_world.cs
Hello, World!
Alternatively:
$ dotnet run hello_world.cs
Hello, World!
That’s all you need to run a C# script, simple and fast!
NuGet Package Dependency
What if you need a NuGet package?
It’s easy. Let’s create a script to show how long until the Year 2038 global overflow problem.
Many computers will crash at 03:14:08 UTC on 19 January 2038 due to Unix epoch signed 32-bit overflow. Our script will show how long until that moment.
Create a new file and make it executable:
touch year_2038_problem.cs
chmod +x year_2038_problem.cs
Add a shebang at the top. Then, add the NuGet package using #:package PackageName@<version>
:
#!/usr/bin/env dotnet run
#:package Humanizer@2.14.1
using Humanizer;
var year2038Problem = DateTimeOffset.Parse("2038-01-19T03:14:08+00:00");
var timeUntil2038Problem = year2038Problem - DateTimeOffset.Now;
Console.WriteLine($"It is {timeUntil2038Problem.Humanize()} until the Year 2038 Problem.");
Run the file in Terminal. Example output:
$ ./year_2038_problem.cs
It is 642 weeks until the Year 2038 Problem.
It is very simple and effective!
ASP.NET Web App
You can also create an ASP.NET app in a single C# file.
Add #:sdk Microsoft.NET.Sdk.Web
at the top after the shebang.
Here’s an example of a C# script for an ASP.NET API that shows the server time.
#!/usr/bin/env dotnet run
#:sdk Microsoft.NET.Sdk.Web
#:package Microsoft.AspNetCore.OpenApi@10.*-*
var builder = WebApplication.CreateBuilder();
builder.Services.AddOpenApi();
var app = builder.Build();
app.MapGet("/", () => DateTimeOffset.Now.ToString());
app.Run();
Conclusion
With .NET 10, you can write scripts in a single file, just like other scripting languages. It’s a great way to automate tasks or prototype ideas.
You can find example scripts in my Git repository:
Questions or suggestions? Feel free to discuss below.
Thanks for reading!