Executing single file csharp files - No .csproj Required
Did you know you can execute a standalone .cs file without creating a project or solution?
With .NET 10 (C# 14), you can run C# files directly using dotnet run.
Create a .cs file and save it. (eg: hello.cs)
Console.WriteLine("Hello world");Execute the file using dotnet run ./hello.cs
No imports necessary as by default this single file execution imports most used libraries.
Behind the scenes the build files are stored in a temporary folder.
This also has unix shebang (#!) support.
#!dotnet run
Console.WriteLine("Hello world");
Adjust the permissions
chmod +x hello.csExecute the program with ./hello.cs
If you also do not want the .cs extension, you can rename the filename mv hello.cs hello and it still works.
Reading command line arguments.
Add the following contents to the .cs file.
if (args.length > 0)
{
string message = string.Join(' ', args);
Console.WriteLine(message)
}You can pass the arguments as follows.
./hello -- This is a command line.The -- option indicates the all following arguments to be passed to the program.
Import nuget packages
You can also import the packages as follows.
#!dotnet run
#:package TextCopy@6.1.0
using TextCopy;
Console.WriteLine(await ClipboardService.GetTextAsync());
When you run this program using ./clipboard.cs, it will output the contents in your clipboard.